Security considerations rfc 2068


Содержание

Security considerations / rfc 2068

Authorization server

The following data elements are stored or accessible on the authorization server:

  • usernames and passwords
  • client ids and secrets
  • client-specific refresh tokens
  • client-specific access tokens
  • HTTPS certificate/key
  • per-authorization process: «redirect_uri», «client_id», authorization «code»

Resource server

The following data elements are stored or accessible on the resource server:

  • user data (out of scope)
  • HTTPS certificate/key
  • either authorization server credentials or authorization server shared secret/public key
  • access tokens (per request)

It is assumed that a resource server has no knowledge of refresh tokens, user passwords, or client secrets.

Client

The following data elements are stored or accessible on the client:

    client id (and client secret or corresponding client credential)

one or more refresh tokens (persistent) and access tokens
(transient) per end user or other security-context or delegation
context

  • trusted certification authority (CA) certificates (HTTPS)
  • per-authorization process: «redirect_uri», authorization «code»
  • bearer token

    A ’bearer token’ is a token that can be used by any client who has received the token (e.g., [RFC6750]). Because mere possession is enough to use the token, it is important that communication between endpoints be secured to ensure that only authorized endpoints may capture the token. The bearer token is convenient for client applications, as it does not require them to do anything to use them (such as a proof of identity). Bearer tokens have similar characteristics to web single-sign-on (SSO)
    cookies used in browsers.

    proof token

    A ’proof token’ is a token that can only be used by a specific client. Each use of the token requires the client to perform some action that proves that it is the authorized user of the token. Examples of this are MAC-type access tokens, which require the client to digitally sign the resource request with a secret corresponding to the particular token sent with the request.

    Безопасность доступа кода

    Чем важна модель безопасности доступа кода (Code Access Security)? С помощью модели безопасности на основе ролей можно указывать, что разрешено делать пользователю, а с помощью модели безопасности доступа кода — что разрешено делать коду. В .NET 4 эта модель упростилась, благодаря удалению необходимости в настройке сложных политик безопасности и добавлению второго уровня прозрачной безопасности (Security Transparency Level 2). Один такой уровень существовал и ранее, а второй является нововведением .NET 4.

    На этом уровне проводится различие между кодом, которому разрешено выполнять привилегированные вызовы (такие как вызовы собственного кода), и кодом, которому это делать не разрешается. Весь код делится на три категории:

    Критичный для безопасности код (Security-Critical Code)

    В рамках этого кода может выполняться любой код. Вызываться из прозрачного кода такой код не может.

    Безопасный код (Safe-Critical Code)

    В рамках этого кода могут выполняться различные проверки на предмет безопасности. Такой код может вызываться из прозрачного кода.

    Прозрачный код

    В рамках этого кода может выполняться очень ограниченное число операций. Этому коду разрешено выполняться только с определенным набором разрешений и только в песочнице (sandbox). В нем не может содержаться никакого небезопасного или непроверяемого кода и вызываться критичный для безопасности код. При написании Windows-приложений ограничение прав кода не применяется.

    Приложения, выполняющиеся в настольной среде, обладают всеми привилегиями доверия и могут содержать любой код. Технология изоляции кода на время выполнения в называемую песочницей (sandbox) ограниченную среду применяется с приложениями SilverLight, а также приложениями ASP.NET, которые обслуживаются веб-провайдером или обладают специфической функциональностью, например, предусматривают запуск дополнительных надстроек за счет использования Managed Add-In Framework.

    Второй уровень прозрачной безопасности

    Сборку можно снабжать атрибутом SecurityRules и устанавливать для него значение SecurityRuleSet.Level2 для применения нового уровня прозрачности, который доступен в .NET 4. (По умолчанию в .NET 4 используется именно этот уровень.) Для обеспечения обратной совместимости для него следует установить значение Level1:

    В случае применения атрибута SecurityTransparent вся сборка не будет делать ничего привилегированного или небезопасного. Она сможет только вызывать какой-то прозрачный или безопасный код. Применять этот атрибут допускается только на уровне всей сборки.

    Атрибут AllowPartiallyTrustedCallers позволяет сделать код чем-то средним между прозрачным кодом и кодом остальных категорий. В случае применения этого атрибута код по умолчанию интерпретируется как прозрачный, но отдельные типы или члены внутри него могут иметь и другие атрибуты:

    Если не применен ни один из этих атрибутов, код считается критическим для безопасности. Однако при желании в нем можно применить атрибут SecuritySafeCritical к отдельным типам и членам и тем самым сделать их пригодными для вызова из прозрачного кода:

    Полномочия

    В случае выполнения кода внутри песочницы указывать, что коду разрешено делать, можно в самой песочнице за счет определения полномочий .NET. Если приложениям, запущенным в настольной среде, предоставляется полный набор полномочий, который позволяет им предпринимать любые действия, то приложениям, выполняющимся в песочнице, предоставляется лишь набор полномочий, который главная среда (хост) передает песочнице и который позволяет выполнять лишь определенные действия. Можно также определять полномочия для домена приложений, запускаемого из настольных приложений. Для этого должен использоваться API-интерфейс Sandbox.

    Под полномочиями, или разрешениями, понимаются действия, которые разрешается (или запрещается) выполнять каждой группе кода. Например, полномочия могут включать в себя «чтение файлов из файловой системы», «выполнение операций записи в Active Directory» и «использование сокетов для открытия сетевых соединений». Есть несколько предопределенных полномочий, и можно также создавать собственные.

    Полномочия .NET не зависят от разрешений операционной системы. Полномочия .NET просто проверяются исполняющей средой. Сборка требует выдачи полномочия для выполнения определенной операции (например, класс File требует выдачи полномочия FileIOPermission), а среда CLR проверяет, чтобы сборке было выдано необходимое полномочие, и она могла продолжить свою работу.

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

    Позволяет управлять возможностью получать доступ к Active Directory с помощью классов System.DirectoryServices.

    DnsPermission

    Позволяет управлять возможностью использования DNS (Domain Name System — служба имен доменов).

    EnvironmentPermission

    Позволяет управлять возможностью выполнять чтение и запись в переменных среды.

    EventLogPermission

    Позволяет управлять возможностью выполнять операции чтения и записи в журнале событий.

    FileDialogPemission

    Позволяет управлять возможностью получать доступ к файлам, которые пользователь выбирает в диалоговом окне Open (Открыть). Обычно такое полномочие применяется в случае невыдачи полномочия FileIOPermission для предоставления хотя бы ограниченного доступа к файлам.

    FileIOPermission

    Позволяет управлять возможностью работать с файлами (чтение, запись и добавление в файлы, а также создание, изменение и доступ к папкам).

    IsolatedStorageFilePermission

    Позволяет управлять возможностью доступа к приватным виртуальным файловым системам.

    IsolatedStoragePermission

    Позволяет управлять возможностью доступа к изолированным хранилищам, т.е. хранилищам, ассоциируемым с отдельными пользователями и имеющими какие-то идентификационные данные в коде.

    MessageQueuePermission

    Позволяет управлять возможностью использования очереди сообщений через службу Microsoft Message Queue.

    PerformanceCounterPermission

    Позволяет управлять возможностью использования счетчиков производительности.

    PrintingPermission

    Позволяет управлять возможностью выполнения печати.

    ReflectionPermission

    Позволяет управлять возможностью обнаружения информации о типах во время выполнения с использованием класса System.Reflection.

    RegistryPermission

    Позволяет управлять возможностью чтения, записи, создания и удаления разделов и параметров в системном реестре.

    SecurityPermission

    Позволяет управлять возможностью выполнения, подтверждения полномочий, вызова неуправляемого кода, пропуска процесса верификации, а также выдачи других прав.

    ServiceControllerPermission

    Позволяет управлять возможностью осуществлять управление службами Windows.

    Socket Permission

    Позволяет управлять возможностью создания или приема соединений TCP/IP по сетевому транспортному адресу.

    SQLClientPermission

    Позволяет управлять возможностью доступа к базам данных SQL Server с помощью предусмотренного в .NET поставщика данных для SQL Server.

    С помощью каждого из этих классов полномочия часто удается задавать даже еще более точно. Например, класс DirectoryServicesPermission позволяет проводить разграничение между полномочиями на выполнение операций чтения и на выполнение операций записи, а также указывать, к каким именно записям в службах каталогов должен быть разрешен или запрещен доступ.

    Наборы полномочий

    Под наборами полномочий понимаются коллекции разрешений. Они избавляют от необходимости применять к коду каждое разрешение отдельно и позволяют группировать необходимые разрешения и применять их к коду сразу вместе. Например, сборка с набором полномочий FullTrust будет иметь полный доступ ко всем ресурсам, а сборка с набором полномочий Local Intranet — лишь ограниченный с возможностью выполнения операций записи только в изолированном хранилище и больше нигде в файловой системе. Допускается создавать собственные наборы полномочий, включающие только определенные разрешения.

    Назначение полномочий группам кода избавляет от необходимости иметь дело с одиночными полномочиями и позволяет применять полномочия сразу целыми блоками, для чего в .NET и предусмотрена концепция наборов полномочий. Эти наборы, по сути, представляют собой списки предоставляемых коду прав, объединенные в именованный набор. Ниже приведено краткое описание семи именованных наборов полномочий, которые поставляются в .NET изначально:

    Тип полномочия Описание
    FullTrust Подразумевает отсутствие всяких ограничений в полномочиях.
    SkipVerification Подразумевает обход верификации.
    Execution Позволяет коду выполняться, но не получать доступ ни к каким защищенным ресурсам.
    Nothing Не предоставляет коду никаких полномочий и не позволяет ему выполняться.
    Local Intranet Предоставляет лишь подмножество из полного набора полномочий. Например, операции файлового ввода-вывода ограничиваются возможностью доступа только для чтения к общему ресурсу, который является источником сборки. В .NET 3.5 и более ранних выпусках (до появления .NET 3.5 с пакетом обновлений SP1) этот набор полномочий применялся в случае выполнения приложения из сетевого общего ресурса.
    Internet Предусматривает использование стандартной политики безопасности для кода неизвестного происхождения. Из всех перечисленных наборов полномочий этот является самым ограниченным. Например, коду, выполняющемуся в рамках этого набора полномочий, не разрешены ни файловые операции ввода-вывода, ни операций чтения и записи журнала событий, ни операции чтения и записи переменных среды.
    Everything Предусматривает выдачу всех перечисленных выше полномочий за исключением SkipVerification. Администратор может изменять любое из полномочий в этом наборе. Это удобно, если необходимо ужесточить стандартную политику безопасности.

    Важно обратить внимание на то, что изменять определения полномочий можно только в наборе Everything (Все); остальные наборы являются фиксированными и изменяться не могут. Разумеется, можно создавать и собственные наборы полномочий.

    Запрос полномочий программным образом

    Сборка может запрашивать полномочия как декларативным, так и программным образом. В следующем фрагменте кода показано, как запрашивать полномочия с помощью метода DemandFileIOPermissions(). После импорта пространства имен System.Security.Permisions можно выполнять проверку на предмет наличия необходимых полномочий, создавая объект FileIOPermission и вызывая его метод Demand().

    Этот метод позволяет проверить, есть ли у кода, вызывающего метод, в данном случае — DemandFileIOPermissions, необходимые полномочия. Если метод Demand() завершается неудачей, генерируется исключение типа SecurityException. Это исключение можно не перехватывать, и предоставлять его обработку вызывающему коду.

    Класс FileIOPermission содержится внутри пространства имен System.Security.Permisions, в котором определен полный набор полномочий, а также классы для декларативных атрибутов полномочий и перечисления для параметров, применяемых для создания объектов полномочий (например, создания объекта FileIOPermission, указывающего, требуется доступ только для чтения или же полный доступ).

    Для перехвата исключений, генерируемых исполняющей средой CLR, когда код пытается выполнить какие-то противоречащие выданным ему полномочиям действия, можно организовать перехват исключения типа SecurityException. Это исключение предоставляет доступ к набору полезных фрагментов информации, в том числе читабельной трассировке стека (SecurityException.StackTrace) и ссылке на метод, который привел к выдаче исключения (SecurityException.TargetSite). Вдобавок SecurityException предоставляет свойство SecurityException.PermissionType, которое возвращает информацию о типе объекта Permission, вызвавшего генерацию исключения.

    В случае применения только классов .NET для операций файлового ввода и вывода самостоятельно запрашивать FileIOPermission не обязательно, поскольку классы .NET, позволяющие производить такие операции, умеют делать это сами. Однако при создании оболочек для вызова собственных методов API-интерфейса, таких как CreateFileTransacted(), его нужно запрашивать самостоятельно. Этот механизм также можно применять для запроса специальных полномочий у вызывающего кода.

    Как настроить Content Security Policy (CSP)

    Три года назад организацией Mozilla Foundation был разработан новый стандарт политики безопасности, который предотвращает XSS-атаки и другие, связанные с ним виды атак запрещая подгружать и выполнять скрипты с запрещённых ресурсов. Называется он Content Security Policy (CSP), что в переводе означает «Политика безопасности контента».

    На момент написания статьи стандарт CSP находится в статусе Candidate Recommendation, что означает возможное принятие этого стандарта в будущем W3C консорциумом. На данный момент все популярные браузеры поддерживают этот стандарт.

    Поддержка Content Security Policy в различных браузерах

    Браузер Версия Примечания
    Chrome 25+ Полная поддержка
    Firefox 23+
    Opera 15+
    Яндекс.Браузер
    Firefox 4-22 Поддерживают нестандартный заголовок X-Content-Security-Policy и частично поддерживают стандартный
    IE 10+
    Chrome 14-24+ Поддерживают нестандартный заголовок X-Webkit-CSP и частично поддерживают стандартный
    Safari 5-7

    Как отсутствие CSP может навредить сайту?

    Допустим у вас есть сайт, на котором вы показываете рекламу пользователям и честно зарабатываете деньги. И всё идёт хорошо, пока к вам не начнут ходит пользователи с заражёнными браузерами. Заражённый браузер будет подменять рекламу на вашем сайте на свою и показывать её пользователю. Как следствие — пессимизация со стороны поисковиков и падение дохода. Если же вы введёте политику CSP на своём сайте, то чужая реклама уже не покажется конечному пользователю, потому что сервер с которого реклама будет пытаться загрузиться находится не в белом списке, впрочем обо всё по порядку.

    Содержание Content Security Policy

    По сути Content Security Policy — это заголовок, который сервер отправляет браузеру. Давайте разберём более детально из чего же он состоит.

    Директивы заголовка CSP

    Директива Назначение
    default-src В этой директиве задаются белые списки хостов, которые будут автоматически присвоены не заданным директивам.
    script-srс Белый список хостов с которых разрешается загрузка javascript
    style-src Белый список хостов с которых разрешается загрузка css
    object-src Белый список хостов с которых разрешается загрузка Flash-подобных плагинов
    img-src Белый список хостов с которых разрешается загрузка картинок
    media-src Белый список хостов с которых разрешается загрузка аудио и видео
    frame-src Белый список хостов с которых разрешается загрузка iframe’ов
    font-src Белый список хостов с которых разрешается загрузка шрифтов
    connect-src Специальные директивы для XMLHttpRequest, WebSocket и EventSource. Обратите внимание, что для каждой из этих директив задаётся список не урлов, а хостов, с которыми разрешено общаться браузеру.
    report-uri Url, на который будет отсылаться JSON-отчёт о нарушениях политики. Пример отчёта будет показан ниже в статье.

    Сейчас ещё немного теории, и потом сразу перейдём к практики, потерпите ��

    Ключевые слова для указания хостов (задаются в кавычках!)

    Ключевое слово Назначение
    ‘self’ Определяет текущий хост.
    ‘none’ Запрещает всё. «You shall not pass!» ��
    ‘unsafe-inline’ Используется только в директивах script-src и style-src . Разрешает выполнять inline-скрипты на странице. Не рекомендую использвать это ключевое слово, т.к. это развязывает руки злоумышленнику и даёт право исполнять любые инлайновые скрипты на странице. Простыми словами, это дыра в безопасности.
    ‘unsafe-eval’ Используется только в script-src и разрешает кодогенерацию, например: eval, new Function, setTimeout(‘var foo = «bar» ‘, 7)

    Устанавливаем Content Security Policy на сайт

    Как я уже писал выше, CSP — это обычный http заголовок, который можно наблюдать в консоли Google Chrome, наряду с остальными заголовками:

    Чтобы лучше понять как работает Content Security Policy, давайте немного поэкспериментируем. Создайте файл index.php и напишите в него следующий код:

    Обратите внимание, что в http заголовке я указал Content-Security-Policy-Report-Only он аналогичен Content-Security-Policy, с той лишь разницей, что не блокирует ресурсы, а только оповещает о нарушении. Крайне полезная штука при тестировании системы перед внедрением!

    Давайте разберёмся, что же мы понаписали. Первым делом мы указали в http заголовке директиву default-src ‘self’ , что означает что подгружать ресурсы можно только со своего хоста. Любые инлайн скрипты и css запрещены. Ок, идём дальше и видим:

    Т.е. попробуем выполнить инлайн скрипт и загрузить картинку со стороннего хоста. И посмотрим как отреагирует наш бравый защитник:

    CSP отреагировал адекватно. Т.е. подгрузил картинку и выполнил инлайновый javascript, но при этом сказал нам в консоли «ата-та!», а именно: сообщил о том, что произошло два нарушения.

    Теперь давайте изменим заголовок с Content-Security-Policy-Report-Only на Content-Security-Policy и посмотрим что будет:

    Пендальф CSP никого не пустил.

    Инлайн скрипт не был выполнен, а картинка не загрузилась. Круто, правда?

    Теперь можете поэкспериментировать самостоятельно. Вам пригодятся две таблички выше в статье, в которых мы рассмотрели директивы и ключевые слова для указания хостов. Попробуйте заменить ‘self’ на http://zabolotskikh.com/ и посмотрите что произойдет — картинка сможет загрузиться, так как её сервер был указан в белом списке.

    Хочу обратить ваше внимание, что хост желательно указывать с протоколом, так как в противном случае протокол будет взят из текущего хоста. Например, если вы укажите хост как zabolotskikh.com , а ваш сервер работает по протоколу https, то в белом списке окажется https://zabolotskikh.com/ .

    Обработка отчётов

    Вся прелесть этой политики в том, что помимо блокирования, мы также можем собирать отчёты о нарушениях! Помните в примере в http заголовке мы указали url report-uri http://localhost/csp/collector.php для сбрасывания отчётов? Как не сложно догадаться на этот url будут отправляться все отчёты о нарушениях.
    Вот так выглядит отчёт о нарушении (в формате JSON):

    С этим отчётом вы можете делать всё что угодно, например сохранять в базу, отправлять на почту. Я предлагаю записывать все нарушения в csv файл. Давайте сделаем это!

    Security Cons >

      Rudolf Julius Bryan 3 years ago Views:

    1 112 SIP Trunking VoIP endpoints and call agents such as CUCM and CUCMExpress also have facilities to control and mark packets. These can be used directly if the enterprise markings are the same as the SP UNI markings, and an SBC can be used if markings need to be translated between the enterprise and the SP networks. Security Considerations The security concerns of TDM trunking, primarily toll fraud, exist equally on SIP trunking. In addition, SIP trunking exposes your network to IP level threats similar to data WAN or Internet access, such as denial of service (DOS). For a hacker to gain access to your enterprise IP network via a TDM voice trunk is virtually impossible to do unless the TDM connection is specifically configured for modem dial-up access and most voice trunks are not. Perpetrating a DOS attack on a TDM trunk is also highly unlikely as it is both expensive to do and requires large-scale autodialer equipment the average Internet hacker does not have access to. Launching these same attacks on IP addresses is significantly easier and open to a much larger pool of perpetrators because no sophisticated equipment is necessary, and the attacks can be launched for free from any Internet access connection. When considering security on SIP trunks, you need to take into account different aspects of security. These aspects call for a series of features and capabilities to mitigate the potential threats. Security is always best deployed in a layered architecture, rather than a single box or feature that strives to protect against all possible attacks. Areas worth exploring for SIP trunk security include Determine the level of exposure on the SIP trunk, which depends on how it is deployed and who the provider is. Limit the devices that can contact your network via the SIP trunk. Mitigation capabilities include features such as access lists, hostname validation, and voice source group definitions. Hide your enterprise network addressing from the outside (which could be Internetvisible) and inspect the validity of traffic that enters your network. Mitigation techniques include network address translation (NAT), topology hiding, firewalls, and intrusion protection services (IPS). Determine protocol and session validity. Mitigation techniques include SIP port settings, SIP protocol inspection and termination, registration, and authentication methods. Lock down your SIP trunk against toll fraud access using the same methods you used on your TDM gateways. Control the privacy of sessions on the SIP trunk. Mitigation techniques involve the control of originator information available outside the enterprise network with the use of SIP privacy headers, SIP normalization, digit manipulation, and encryption

    2 Chapter 7: Design and Implementation Considerations 113 methods of the signaling and the media streams (such as Transport Layer Security [TLS], Secure RTP, and the use of IPSec tunnels or virtual private networks (VPN) on the IP connections). SIP Trunk Levels of Security Exposure The level of security exposure depends on the characteristics of how the SIP trunk connects into your network and the strength of security protection your service provider offers. Figure 7-2 illustrates four increasing levels of exposure depending on the connectivity method of your SIP trunk: (a) SIP Trunk SIP SP Increased Threat Level (b) (c) SIP Trunk WAN Data SIP Trunk Internet Data SIP + VPN SP SIP SP + Internet (d) Internet Voice Internet Data Internet Figure 7-2 Increasing Levels of Security Exposure In model (a) the SIP trunk connects from a Tier 1 service provider with strong security over a dedicated physical connection into your network. No data traffic traverses this connection. With this model, your security exposure is low, and you can consider not having a firewall in addition to a border element on such a connection. In model (b) the SIP trunk connects from a Tier 1 service provider with strong security over a physical connection that carries both your voice and your VPN WAN data connection, such as an MPLS service. No Internet data traffic traverses this connection. With this model, your security exposure is still fairly low, and you might not need a firewall in addition to a border element on such a connection.


    3 114 SIP Trunking In model (c) the SIP trunk connects from a service provider that offers both SIP trunking and Internet access on the same physical connection. This is often a costeffective model for smaller businesses with no WAN data service between sites or that have only a single site. Regardless of the strength of security measures in the service provider s network, you are exposed to Internet attacks on this kind of connection, and you have to firewall in addition to deploying a border element to secure this type of connection. In model (d) there is no SIP trunk service offering, and you use plain Internet consumer voice access and Internet data from a general Internet service provider. This model is strongly discouraged for business-class voice access because there is no quality control on such a connection, and it is extremely exposed to all kinds of voice and data Internet attacks. Firewalling and border controlling alone are still not sufficient to make this model capable of providing business-quality voice services. Many security features on both firewalls and border elements protect against attacks on SIP trunks. The following sections discuss these techniques in more detail. A general best practice for SIP trunk security is always to use a border element to terminate a SIP trunk coming into your network. This can be an appliance function (such as deploying a dedicated ), or it can be an integrated function, such as an IAD or CUCM Express device that acts as a border element and a routing or IP-PBX device in your network. In addition to a border element, you can choose also to deploy a firewall. Again, this might be a separate appliance, or it might be integrated into a Cisco IOS router providing multiple functions to your business. Separate, dedicated devices tend to be the norm for larger enterprise and higher volume SIP trunks, whereas integrated devices tend to be the cost-effective solution for smaller sites or small business networks. Access Lists (ACL) Always strictly limit the devices that can access your SIP trunk, both from internal to your network and external to it. If you terminate your SIP trunk on a border element, you do not need all these security mitigation measures on every enterprise application, only on the border element. The border element itself should be set up to accept connections on the service provider side only from the provider s SBC, and on the enterprise side only from legitimate CUCM, IP-PBX, or other valid applications (for example, SIP proxies and meeting conference servers). United States federal information reports that hackers are as frequently located inside your enterprise network as on the outside, and for that reason, it is imperative to lock down your border element on both sides so that rogue endpoints and applications inside your network cannot use the SIP trunk service for fraudulent calls. Similarly, rogue endpoints on the Internet should contact your SIP trunk. This configuration is illustrated in Figure 7-3.

    4 Chapter 7: Design and Implementation Considerations 115 access-list 1 permit access-list 100 deny (everything else) access-list 2 permit access-list 200 deny (everything else) SP VolP IP Figure 7-3 Locking Down a SIP Trunk with ACLs Additionally, voice Source IP Groups can be used with the ACLs, as shown in Figure 7-3, to provide further restrictions on the devices that might originate SIP traffic to your border element. On devices in your network that should not run SIP traffic at all, the Control Plane Policing (CoPP) feature can be used to deny all SIP traffic. CUCM has (by default) a feature that restricts traffic on a SIP trunk to be accepted only from the IP address configured on the SIP trunk. Hostname Validation You can use the hostname validation feature of the to restrict the valid hostnames that are accepted in the host portion of the SIP URI of an incoming SIP INVITE. Example 7-1 illustrates the commands used by this feature to enable calls only from the four hostnames listed. Example 7-1 Hostname Validation sip-ua permit hostname dns:example1.sip.com permit hostname dns:example2.sip.com permit hostname dns:example3.sip.com permit hostname dns:example4.sip.com Security features often overlap to some extent, and it is a good practice to deploy these overlapping features because they provide layered security protection. Every layer might protect you against one particular attack that might have skirted around a single layer protection to exploit a weakness in a particular appliance, device, feature operation, or configuration.

    5 116 SIP Trunking NAT and Topology Hiding Hiding the IP addresses of enterprise voice endpoints (such as those belonging to IP phones, call agents, and TDM voice gateways) from external view can in some cases be achieved with traditional NAT features. NAT adjusts the IP addressing of IP packet headers and some of the IP addresses appearing elsewhere in SIP packets, but generic NAT devices are Layer 3-capable only. Those that have Application Layer Gateways (ALG) have more sophisticated SIP awareness, but still, generally, might offer only suboptimal capabilities to translate deeply embedded IP addresses in SIP messaging. It is therefore more secure to use a border element that is a full SIP back-to-back user agent (B2BUA) as the network demarcation offering 100 percent SIP packet inspection and address translation. The is a full SIP B2BUA and can therefore offer complete network address translation, usually referred to as topology hiding in this context to distinguish this function from appliance NAT devices. Both media and signaling flow through the and the service provider and off-net endpoints see only the addresses of the border element and never the addresses internal to your enterprise network. Topology hiding is important to ensure that any attacks that might come from the service provider side can be directed only toward the border element, and the communications and call agents within your enterprise remain unaffected. Figure 7-4 illustrates how topology hiding can be accomplished by using the IP Inside Outside Inside Site A x/ x/24 Site B x/24 Figure 7-4 Topology Hiding Firewalls Many security features on both firewalls and border elements protect against attacks on SIP trunks. A certain amount of overlap occurs between the capabilities, especially true for the higher end firewalls with sophisticated SIP ALGs. Generally you should deploy a firewall to provide generic IP protection against any kind of IP traffic, and your border element as a much more focused, voice-specific session protection function. For the least capable firewall devices, you should simply open pinholes for the traffic destined to the border element and have the border element do all the SIP inspection. For firewalls with SIP ALGs, there is some overlap in the inspection the firewall does and the inspection done by the border element. The border element always

    6 Chapter 7: Design and Implementation Considerations 117 provides the most sophisticated layer of protection because it is a B2BUA whereas the firewall essentially inspects and passes through traffic but does not terminate it. Functions that firewalls are particularly well suited to mitigate are Layers 2 and 3 inspection functions including: General IP DOS attacks Black hole routing TCP window control and dropping UDP packets Access lists, specifying what traffic is correct and allowed Optional SIP ALG for cursory SIP rogue and malformed packet inspection Optional SIP ALG protection against spikes of SIP calls (SIP-specific DOS) More sophisticated SIP capabilities that some firewalls can have include Whitelist/blacklist filtering of SIP calls based on calling and called numbers Rate limiting of specific SIP methods to mitigate against SIP-specific DOS attacks Firewalls are not as well suited to protecting against attacks launched from inside your network or doing session management at the level of deciding whether packets are arriving for valid sessions only, in valid sequences (or SIP dialogs), and for valid codecs or other negotiated parameters of the session. Some of the more sophisticated firewalls, such as the Cisco ASA product series or the Cisco IOS Firewall, have SIP ALGs that offer some protection services at protocol layers higher than Layer 3. Specific functions a border element is well suited for include Layers 5 to 7 SIP inspection actions such as: Rejecting nonallowed calls and generating CDRs of call attempts for tracking Call limiting (only accept a certain number of calls) Codec limiting (only accept certain codecs) Call admission control to provide bandwidth protection Access lists specifying valid source and destination call agents Complete rogue and malformed SIP packet protection Digest authentication and hostname validation to ensure sessions are set up only between valid endpoints SIP registration to authenticate session originations SIP listening port configuration

    7 118 SIP Trunking Broadly, firewalls and border elements are deployed in one of two ways: Separate devices in series Integrated in a Cisco IOS device with collocated functions Figure 7-5 provides six possible deployment models of firewalls and border elements. (a) (d) SP SP (b) (e) SP SP (c) (f) SP SP Figure 7-5 Possible Firewall and Border Element Designs Models (a), (b), and (c) shown in Figure 7-5 are better suited to medium-to-large enterprises and high volume contact centers, and models (d), (e), and (f) are better suited to smaller businesses. In model (a) the firewall appliance is on the outside of the border element. This is the recommended deployment model if you use separate devices for firewall services and a border element. This deployment generally makes sense for campus and data center locations where there is already a firewall present. This model also makes sense if the firewall is managed by the security team, whereas the border element is managed by the voice team. This is a mandatory model if the physical medium coming into the enterprise premises carries Internet traffic. In this model, the firewall provides the first line of defense on all traffic arriving from the outside, passes the voice traffic to the border element for a Layer 7 inspection on the voice traffic. If the firewall has an ALG function, there is bound to be some overlap in functionality between the firewall and the border element. It is nevertheless recommended that you turn on both to get the fullest set of inspection and protection that you can, rather than having potential security holes between the appliances. In model (b) the border element is on the outside of the firewall. This deployment model makes sense when the physical medium bringing the SIP trunk into your

    8 Chapter 7: Design and Implementation Considerations 119 premises carries only SIP trunk traffic and nothing else. This means your data connections come in on a different physical path, onto different routers, and get firewalled entirely separately from the SIP trunk traffic. This model mandates that you trust your service provider s network to offer only clean SIP traffic to your enterprise. In model (c) two firewalls are on either side of the border element. Some refer to this model as the one for the truly paranoid, but this is the classic design of a DMZ (demilitarized zone). It is not an uncommon design, especially in large financial, educational, and government institutions, or any other business particularly attractive to hackers. Model (d) is a variation of model (c), where there are two virtual firewalls on either side of the border element, but one physical firewall device is used for the function, routing the unified communications (UC) traffic twice. This is a virtual DMZ design often used in video deployments where the is not only fronting a SIP trunk, but is also bringing in H.323 Internet video traffic and acting as a Cisco IOS Gatekeeper. Model (e) provides a more cost-effective integrated deployment model for smaller sites or businesses where a separate firewall appliance does not already exist, is not desirable, or the cost is not justified. In this model the Cisco IOS router acts as both the and the firewall. Traffic flowing through this router is inspected first by the firewall and then handed to the border element for further processing. It is therefore conceptually similar to model (a). Model (f) provides a lower end offering for commercial or small businesses (without IT departments) that do not want to carry the cost or the management of either a border element or a firewall. In this model, an integrated service from a service provider is purchased, and all security and demarcation issues is handled by the service provider. The service provider puts an IAD at the customer premises to connect to its IP-PBX or key system, such as CUCM Express. The IAD device will likely do NAT, perhaps basic firewalling, but essentially all the service provider s network and security are delivered as a managed service. Security Protection at the SIP Protocol Level SIP is a widely used and understood protocol and simple to create because it uses straight text encoding in its messages (unlike H.323 that uses ASN.1 encoding). This makes SIP an easy target for hackers. Many of the protocol attacks can be launched against H.323 as well, but very few incidents of this were in the industry because H.323 is not as accessible as SIP. Several ways to protect your network against a variety of SIP protocol attacks include Setting the SIP listening port Using TLS for authentication Using a border element B2BUA

    9 120 SIP Trunking Using SIP normalization techniques to suppress or overwrite information in the SIP message such as the calling phone numbers, hostnames, or descriptive tags before a call enters the public network Using digit manipulation techniques to suppress or overwrite phone numbers before a call enters the public network Using SIP privacy settings to communicate the information within the SIP message that might or might not be used Each of these areas is discussed in the following sections. SIP Listening Port Every Internet hacker knows the default SIP listen ports and can sweep them from any Internet location to find an open port to launch fraudulent calls, all while your business pays for them. One way to protect against this is to change the SIP listening port to a nondefault setting. It requires the service provider to set the complementary port on the provider edge SBC. This alone can protect you against the majority of hacker attacks launched against SIP port Example 7-2 shows the commands needed to set the SIP listening port to a nondefault setting. Example 7-2 SIP Listening Port Setting voice service voip sip shutdown voice service voip sip listen-port non-secure 2000 secure 2050 voice service voip sip no shutdown Transport Layer Security (TLS) Another way to protect against this attack is to use TLS (specified in IETF RFC-2246). TLS uses an authentication mechanism that ensures only valid endpoints connect to your SIP trunk, and if the authentication fails, the call is refused. Although this is a good way to mitigate fraudulent SIP calls, none of the current SIP trunk offerings in the market include TLS as an option. Hopefully this situation will change.

    10 Chapter 7: Design and Implementation Cons > Example 7-4 Original SIP INVITE INVITE sip: SIP/2.0 Via: SIP/2.0/UDP :5060;branch=z9hG4bK1AD9E2 Remote-Party- >

    11 122 SIP Trunking Example 7-5 Normalized SIP INVITE (continued) To: Date: Thu, 30 Aug :04:36 GMT Digit Manipulation Another technique to suppress or change nonpublic numbers from exiting your network is to use digit manipulation techniques at the border of your network. For example, a non-did number can be changed to your organization s basic public PSTN number if the call should go off-net. SIP Privacy Methods Various SIP specifications control the privacy of end user information in SIP messaging such that numbers and names can travel in the messaging but still be suppressed from delivery or display to the destination endpoint. Similar methods exist in ISDN when interconnecting to the traditional PSTN. SIP specifications (and capabilities) of interest in this area include The Privacy SIP header (RFC-3323) provides guidelines for withholding the identity of a person (and related personal information) from one or more parties in an exchange of SIP communications. The P-Asserted-Identity (PAI) and P-Preferred-Identity (PPI) (RFC-3325) headers provide extensions that enable the communication of the identity of authenticated users and the application of existing SIP privacy mechanisms to communicating these identities. If your applications are not SIP-capable, or if they do not insert these headers, you can have your border element insert (or change) the content of these headers as a call leaves your premises over the SIP trunk. The can also convert between the widely deployed Remote-Party-ID (RPID) header to and from PAI/PPI and Privacy headers. Registration and Authentication You can use SIP mechanisms to validate the originator of a SIP call and therefore provide a mechanism to reject SIP INVITEs that come from rogue endpoints. These mechanisms include Registration: Some service provider SIP trunk offerings include a registration sequence enabling the enterprise edge to register explicitly with the provider s SIP softswitch. Some SIP applications are capable of this; if not you can have your do the registration on behalf of the endpoints behind it in the enterprise network. Digest Authentication (RFC-2617): A SIP softswitch can challenge the INVITEs, and the originator must respond with credentials that are then authenticated by the SIP softswitch. Unlike a SIP registration sequence that happens once, the Digest

    12 Chapter 7: Design and Implementation Considerations 123 Authentication happens on every SIP INVITE. The can respond to Digest Authentication challenges with configured credentials. Example 7-6 shows sample commands to configure the to do a SIP registration with credentials, and Example 7-7 shows the configuration for SIP Digest Authentication. Example 7-6 SIP Registration x(config)#sip-ua x(config-sip-ua)#credentials username 1001 password cisco realm cisco.com sip-ua registrar ipv4: expires 3600 credentials username 1001 password D0A16 realm cisco.com Example 7-7 SIP Digest Authentication sip-ua authentication username xxx password yyy Toll Fraud Toll fraud has existed for as long as telephone networks have been in operation. This constitutes making unauthorized calls that someone else pays for. The perpetrator can be inside your network (for example, an employee making personal international calls) or an external hacker using your SIP trunk to make calls that your company pays for. Ensure that whatever measures you took to combat toll fraud in your TDM PSTN access network are also implemented on your SIP trunk PSTN access network. Some of the common tools that enable you to mitigate toll fraud attacks include Use ACLs to enable explicit sources of calls and deny all other traffic. Apply explicit incoming and outgoing dial-peers to both Border Element interfaces to control the types and parameters of calls allowed through the network border. If an incoming dial-peer is not found for a call, the system default dial-peer 0 is used enabling all calls; to avoid this, specify explicit incoming dial-peers for valid call flows and deny all other calls. Use explicit destination-patterns on dial-peers (try to avoid using.t if you can) to block out disallowed off-net call destinations. Use translation rules to ensure only valid calling/called numbers are allowed. This allows you to add access codes dialing to gain entry to certain destinations (for example, international destinations). Your employees know these access codes, but off-net hackers do not. Use Tool Command Language (Tcl) or Voice Extensible Markup Language (VoiceXML) scripts to do database lookups or require PINs or authorization codes

    13 124 SIP Trunking for additional validity checks to allow/deny call flows. This method protects against internal fraudulent calls. Change the SIP listening port to something other than the default of Close unused H.323 or SIP ports if your Border Element is connected purely to a SIP trunk, there is no need for the H.323 ports to be open. The Class of Restriction (COR) feature restricts call attempts based on both the incoming and outgoing dial-peers matched by the call. Signaling and Media Encryption Another area of security to consider is the privacy of communications, that is, how to keep hackers from recording calls or hijacking them and inserting or deleting segments. Several encryption features for voice call flows mitigate these types of attacks. Separate features for protection of the signaling traffic (TCP or UDP) and the media traffic (RTP) exist. Signaling encryption can be achieved by IPsec tunnels (both TCP and UDP SIP traffic) or TLS (SIP TCP). You can use TLS just for authentication or also for encryption of the signaling stream. You can achieve media encryption with Secure RTP (SRTP) (RFC-3711). As the media encryption keys are exchanged in the signaling stream, there is no point in encrypting media without also encrypting the signaling. Only encrypting signaling is a valid option. None of the current SIP trunk offerings in the market include TLS or SRTP as an option. Hopefully this situation will change. The can convert between encrypted communications (TLS/SRTP) on one side and nonencrypted (SIP/RTP) on the other side, so if your business can benefit from (or demands) encryption in the enterprise, you can still connect to a SIP trunk provider. Session Management, Call Traffic Capacity, Bandwidth Control, and QoS Managing simultaneous voice call capacity and IP bandwidth use is essential for providing consistent quality in enterprise communications. Areas regarding session management and CAC to be considered in the design of your network include Trunk provisioning Bandwidth adjustments and consumption Call admission control

    Content Security Policy

    W3C Cand > 3 September 2014

    Abstract

    This document defines a policy language used to declare a set of content restrictions for a web resource, and a mechanism for transmitting the policy from a server to a client where the policy is enforced.

    Status of this document

    This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

    This document was published by the Web Application Security Working Group as a Candidate Recommendation. This document is intended to become a W3C Recommendation.

    The (archived) public mailing list public-webappsec@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “CSP2” in the subject, preferably like this: “[CSP2] …summary of comment…

    Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

    The entrance criteria for this document to enter the Proposed Recommendation stage is to have a minimum of two independent and interoperable user agents that implementation all the features of this specification, which will be determined by passing the user agent tests defined in the test suite developed by the Working Group.

    This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An indiv > This document is governed by the 1 August 2014 W3C Process Document.

    The following features are at-risk, and may be dropped during the CR period:

    • §3.4 The CSP HTTP Request Header
    • §7.2 child-src

    Table of Contents

    1 Introduction

    This section is not normative.

    This document defines Content Security Policy, a mechanism web applications can use to mitigate a broad class of content injection vulnerabilities, such as cross-site scripting (XSS). Content Security Policy is a declarative policy that lets the authors (or server administrators) of a web application inform the client about the sources from which the application expects to load resources.

    To mitigate XSS attacks, for example, a web application can declare that it only expects to load script from specific, trusted sources. This declaration allows the client to detect and block malicious scripts injected into the application by an attacker.

    Content Security Policy (CSP) is not intended as a first line of defense against content injection vulnerabilities. Instead, CSP is best used as defense-in-depth, to reduce the harm caused by content injection attacks. As a first line of defense against content injection, server operators should validate their input and encode their output.

    There is often a non-trivial amount of work required to apply CSP to an existing web application. To reap the greatest benefit, authors will need to move all inline script and style out-of-line, for example into external scripts, because the user agent cannot determine whether an inline script was injected by an attacker.

    To take advantage of CSP, a web application opts into using CSP by supplying a Content-Security-Policy HTTP header. Such policies apply to the current resource representation only. To supply a policy for an entire site, the server needs to supply a policy with each resource representation.

    1.1 Changes from 1.0

    This document describes an evolution of the Content Security Policy specification. Level 2 makes two breaking changes, and adds support for a number of new directives and capabilities which are summarized below:

      The following changes are backwards incompatible with the majority of user agent’s implementations of CSP 1:

        The path component of a source expression is now ignored if the resource being loaded is the result of a redirect, as described in §4.2.2.3 Paths and Redirects.

      Note: Paths are technically new in CSP2, but they were already implemented in many user agents before this revision of CSP was completed, so noting the change here seems reasonable.

    1. Redirects are blocked by default, and explicitly allowed with a new unsafe-redirect expression.
    2. A protected resource’s ability to load Workers is now controlled via child-src rather than script-src .
    3. Workers now have their own policy, separate from the protected resource which loaded them. This is described in §5.1 Workers.
  • The following directives are brand new in this revision:
    1. base-uri controls the protected resource’s ability to specify the document base URL.
    2. child-src deprecates and replaces frame-src , controlling the protected resource’s ability to embed frames, and to load Workers.
    3. form-action controls the protected resource’s ability to submit forms.
    4. frame-ancestors controls the protected resource’s ability be embedded in other documents. It is meant to supplant the X-Frame-Options HTTP request header.
    5. plugin-types controls the protected resource’s ability to load specific types of plugins.
    6. referrer controls the protected resource’s referrer policy [REFERRER].
    7. reflected-xss controls the user agent’s built-in heuristics to actively protect against XSS. It is meant to supplant the X-XSS-Protection HTTP request header.
  • Individual inline scripts and stylesheets may be whitelisted via nonces (as described in §4.2.4 Valid Nonces) and hashes (as described in §4.2.5 Valid Hashes).
  • A CSP request header is now sent with relevant requests, as described in §3.4 The CSP HTTP Request Header.
  • A SecurityPolicyViolationEvent is fired upon violations, as described in §6.3 Firing Violation Events.
  • A number of new fields were added to violation reports (both those POSTED via report-uri , and those handed to the DOM via SecurityPolicyViolationEvent events. These include effectiveDirective , statusCode , sourceFile , lineNumber , columnNumber .
  • 2 Key Concepts and Terminology

    This section defines several terms used throughout the document.

    The term refers to either:

    1. a set of security preferences for restrictions within which the content can operate, or
    2. a fragment of text that codifies these preferences.

    The security policies defined by this document are applied by a user agent on a per-resource representation basis. Specifically, when a user agent receives a policy along with the representation of a given resource, that policy applies to that resource representation only. This document often refers to that resource representation as the .

    A is a portion of a policy that declares the specific set of restrictions for a particular resource type, or which manipulates a specific aspect of a protected resource’s configuration. A server transmits its security policy for a particular protected resource as a collection of directives, such as default-src ‘self’ , each of which declares a specific set of restrictions for that resource as instantiated by the user agent. More details are provided in the §7 Directives section.

    A directive consists of a , which indicates the privileges controlled by the directive, and a , which specifies the restrictions the policy imposes on those privileges.

    The term is defined in the Origin specification. [RFC6454]

    The term is defined in section 4 of the Origin specification. Note that URLs that do not use hierarchical elements as naming authorities have origins which are globally unique identifiers. [RFC6454]

    The term is defined in the URI specification. [URI]

    The term is defined Section 3 of HTTP/1.1 — Semantics and Content [RFC7231]

    The terms and are defined in the JSON specification. [RFC4627]

    The applet , audio , embed , iframe , img , link , object , script , source , track , and video elements are defined in the HTML5 specification. [HTML5]

    A plugin is defined in the HTML5 specification. [HTML5]

    The Cascading Style Sheets (CSS) rule is defined in the CSS Fonts Module Level 3 specification. [CSS3-FONTS]

    The XMLHttpRequest object is defined in the XMLHttpRequest specification. [XMLHTTPREQUEST]

    The WebSocket object is defined in the WebSocket specification. [WEBSOCKETS]

    The EventSource object is defined in the EventSource specification. [EVENTSOURCE]

    The Augmented Backus-Naur Form (ABNF) notation used in this document is specified in RFC5234. [ABNF]

    This document also uses the ABNF extension «#rule» as defined in Section 7 of HTTP/1.1 — Message Syntax and Routing. [RFC7230]

    The following core rules are included by reference, as defined in Appendix B.1 of [ABNF]: ALPHA (letters), DIGIT (decimal 0-9), WSP (white space) and VCHAR (printing characters).

    , , and are the digest algorithms defined by the NIST.

    The term refers to an object whose interface has one or more as defined in the Web IDL specification [WEBIDL].

    An is defined in Section 6.3.1 of HTTP/1.1 — Semantics and Content [RFC7231]

    3 Policy Delivery

    The server delivers the policy to the user agent via an HTTP response header or an HTML meta element. Servers are informed that requests are subject to a policy via an HTTP request header.

    3.1 Content-Security-Policy Header Field

    The header field is the preferred mechanism for delivering a policy.

    A server MAY send more than one HTTP header field named Content-Security-Policy with a given resource representation.

    A server MAY send different Content-Security-Policy header field values with different representations of the same resource or with different resources.

    Upon receiving an HTTP response containing at least one Content-Security-Policy header field, the user agent MUST enforce each of the policies contained in each such header field.

    3.2 Content-Security-Policy-Report-Only Header Field

    The header field lets servers experiment with policies by monitoring (rather than enforcing) a policy.

    For example, server operators might wish to develop their security policy iteratively. The operators can deploy a report-only policy based on their best estimate of how their site behaves:

    If their site violates this policy the user agent will send violation reports to the URI specified in the policy’s report-uri directive, but allow the violating resources to load regardless. Once a site has confidence that the policy is appropriate, they can start enforcing the policy using the Content-Security-Policy header field.

    A server MAY send more than one HTTP header field named Content-Security-Policy-Report-Only with a given resource representation.

    A server MAY send different Content-Security-Policy-Report-Only header field values with different representations of the same resource or with different resources.

    Upon receiving an HTTP response containing at least one Content-Security-Policy-Report-Only header field, the user agent MUST monitor each of the policies contained in each such header field.

    Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element.

    3.3 HTML meta Element

    The server MAY supply a policy in an HTML meta element with an http-equiv attribute that is a case insensitive match for the string » Content-Security-Policy «. For example:

    Add the following entry to the pragma directives for the meta element: Content security policy ( http-equiv=»content-security-policy» )

    1. If the Document’s head element is not an ancestor of the meta element, abort these steps.
    2. If the meta element lacks a content attribute, abort these steps.
    3. Let policy be the value of the content attribute of the meta element.
    4. Let directive-set be the result of parsing policy .
    5. Remove all occurrences of reflected-xss , report-uri , and sandbox directives from directive-set .
    6. Enforce each of the directives in directive-set , as defined for each directive type.

    Authors are strongly encouraged to place the meta element as early in the document as possible to reduce the risk of content injection before a protective policy can be read and enforced.

    Note: A policy specified via a meta element will be enforced along with any other policies active for the protected resource, regardless of where they’re specified. The general mechanism for determining the effect of enforcing multiple policies is detailed in the §3.5 Enforcing multiple policies. section.

    Note: Modifications to the content attribute of a meta element after the element has been parsed will be ignored.

    Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element.

    3.4 The CSP HTTP Request Header

    The header field indicates that a particular request is subject to a policy, and its value is defined by the following ABNF grammar:

    If the user agent is monitoring or enforcing a policy that includes directives whose value is a source list, and whose source list contains the ‘unsafe-redirect’ source expression, then the user agent MUST send a header field named CSP along with requests for resources whose origin does not match the protected resource’s origin. The value of this header MUST be active .

    The user agent MAY choose to send this header only if the request is for a resource type which the active policy would effect. That is, given a policy of img-src example.com ‘unsafe-redirect’ , the user agent would send CSP: active along with requests for images, but might choose not to send the header with requests for script.

    Note: The central reason for including this header is that it hints to a server that information about redirects might be leaked as a side-effect of a page’s active policy. If this header is present, a server might decline to redirect a logged-out user from example.com to accounts.example.com , for example, as a malicious embedder might otherwise be able to determine the user’s logged-in status.

    3.5 Enforcing multiple policies.

    This section is not normative.

    The above sections note that when multiple policies are present, each must be enforced or reported, according to its type. An example will help clarify how that ought to work in practice. The behavior of an XMLHttpRequest might seem unclear given a site that, for whatever reason, delivered the following HTTP headers:

    Is a connection to example.com allowed or not? The short answer is that the connection is not allowed. Enforcing both policies means that a potential connection would have to pass through both unscathed. Even though the second policy would allow this connection, the first policy contains connect-src ‘none’ , so its enforcement blocks the connection. The impact is that adding additional policies to the list of policies to enforce can only further restrict the capabilities of the protected resource.

    To demonstrate that further, consider a script tag on this page. The first policy would lock scripts down to ‘self’ , http://example.com and http://example.net via the default-src directive. The second, however, would only allow script from http://example.com/ . Script will only load if it meets both policy’s criteria: in this case, the only origin that can match is http://example.com , as both policies allow it.

    3.6 Policy applicability

    This section is not normative.

    Policies are associated with an protected resource, and enforced or monitored for that resource. If a resource does not create a new execution context (for example, when including a script, image, or stylesheet into a document), then any policies delivered with that resource are discarded without effect. Its execution is subject to the policy or policies of the including context. The following table outlines examples of these relationships:

    Resource Type What policy applies?
    Top-level Contexts HTML as a new, top-level browsing context The policy delivered with the resource
    SVG, as a top-level document Policy delivered with the resource
    Embedded Contexts Any resource included via iframe, object, or embed The policy of the embedding resource controls what may be embedded. The embedded resource, however, is controlled by the policy delivered with the resource, or the policy of the embedding resource if the embedded resource is a globally unique identifier (or a srcdoc frame).
    SVG, as an embedded document The policy delivered with the resource, or policy of the creating context if created from a globally unique identifier.
    JavaScript, as a Worker, Shared Worker or Service Worker The policy delivered with the resource, or policy of the creating context if created from a globally unique identifier
    Subresources SVG, inlined via svg Policy of the including context
    SVG, as a resource document Policy of the including context
    HTML via XMLHttpRequest Policy of the context that performed the fetch
    Image via img element Policy of the including context
    JavaScript via a script element Policy of the including context
    SVG, via img No policy; should be just as safe as JPG
    SVG, as a WebFont No policy; should be just as safe as WOFF

    4 Syntax and Algorithms

    4.1 Policy Syntax

    A Content Security Policy consists of a U+003B SEMICOLON ( ; ) delimited list of directives. Each directive consists of a directive name and (optionally) a directive value, defined by the following ABNF:

    4.1.1 Parsing Policies

    To policy , the user agent MUST use an algorithm equivalent to the following:

    1. Let the set of directives be the empty set.
    2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON ( ; ):
      1. Skip whitespace.
      2. Collect a sequence of characters that are not space characters. The collected characters are the directive name .
      3. If there are characters remaining in token , skip ahead exactly one character (which must be a space character).
      4. The remaining characters in token (if any) are the directive value .
      5. If the set of directives already contains a directive whose name is a case insensitive match for directive name , ignore this instance of the directive and continue to the next token.
      6. Add a directive to the set of directives with name directive name and value directive value .


    3. Return the set of directives .

    4.2 Source List Syntax

    Many CSP directives use a value consisting of a , defined in the ABNF grammar below.

    Each in the source list represents a location from which content of the specified type can be retrieved. For example, the source expression ‘none’ represents the empty set of URIs, and the source expression ‘unsafe-inline’ represents content supplied inline in the resource itself.

    If the policy contains a nonce-source expression, the server MUST generate a fresh value for the nonce-value directive at random and independently each time it transmits a policy. This requirement ensures that the nonce-value is difficult for an attacker to predict.

    The host-char production intentionally contains only ASCII characters; internationalized domain names cannot be entered directly into a policy string, but instead MUST be Punycode-encoded [RFC3492]. For example, the domain üüüüüü.de would be encoded as xn--tdaaaaaa.de .

    4.2.1 Parsing Source Lists

    To source list , the user agent MUST use an algorithm equivalent to the following:

    1. Strip leading and trailing whitespace from source list .
    2. If source list is a case insensitive match for the string ‘none’ (including the quotation marks), return the empty set.
    3. Let set of source expressions be the empty set.
    4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression , add the token to the set of source expressions .
    5. Return the set of source expressions .

    Note: Characters like U+003B SEMICOLON ( ; ) and U+002C COMMA ( , ) cannot appear in source expressions directly: if you’d like to include these characters in a source expression, they must be percent encoded as %3B and %2C respectively.

    4.2.2 Matching Source Expressions

    A URI is said to if the following algorithm returns does match:

    1. Normalize the URI according to Section 6 of RFC3986.
    2. If the source expression a consists of a single U+002A ASTERISK character ( * ), and the URI’s scheme is not of a type designating a globally unique identifier, (such as blob: , data: , or filesystem: ) then return does match.
    3. If the source expression matches the grammar for scheme-source :
      1. If the URI’s scheme is a case-insensitive match for the source expression’s scheme-part , return does match.
      2. Otherwise, return does not match.
    4. If the source expression matches the grammar for host-source :
      1. If the URI does not contain a host, then return does not match.
      2. Let uri-scheme , uri-host , and uri-port be the scheme, host, and port of the URI, respectively. If the URI does not have a port, then let uri-port be the default port for uri-scheme . Let uri-path be the path of the URI after decoding percent-encoded characters. If the URI does not have a path, then let uri-path be the U+002F SOLIDUS character ( / ).
      3. If the source expression has a scheme-part that is not a case insensitive match for uri-scheme , then return does not match.
      4. If the source expression does not have a scheme, return does not match if
        1. the scheme of the protected resource’s URI is a case insensitive match for HTTP , and uri-scheme is not a case insensitive match for either HTTP or HTTPS
        2. the scheme of the protected resource’s URI is not a case insensitive match for HTTP , and uri-scheme is not a case insensitive match for the scheme of the protected resource’s URI.
      5. If the first character of the source expression’s host-part is an U+002A ASTERISK character ( * ) and the remaining characters, including the leading U+002E FULL STOP character ( . ), are not a case insensitive match for the rightmost characters of uri-host , then return does not match.
      6. If the first character of the source expression’s host-part is not an U+002A ASTERISK character ( * ) and uri-host is not a case insensitive match for the source expression’s host-part , then return does not match.
      7. If the source expression does not contain a port-part and uri-port is not the default port for uri-scheme , then return does not match.
      8. If the source expression does contain a port-part , then return does not match if
        1. port-part does not contain an U+002A ASTERISK character ( * ), and
        2. port-part does not represent the same number as uri-port .
      9. If the source expression contains a non-empty path-part , and the URI is not the result of a redirect, then:
        1. Let decoded-path be the result of decoding path-part ’s percent-encoded characters.
        2. If the final character of decoded-path is the U+002F SOLIDUS character ( / ), and decoded-path is not a prefix of uri-path , then return does not match.
        3. If the final character of decoded-path is not the U+002F SOLIDUS character ( / ), and decoded-path is not an exact match for uri-path then return does not match.
      10. Otherwise, return does match.
    5. If the source expression is a case insensitive match for ‘self’ (including the quotation marks), then:
      1. Return does match if the URI has the same scheme, host, and port as the protected resource’s URI (using the default port for the appropriate scheme if either or both URIs are missing ports).
    6. Otherwise, return does not match.

    A URI is said to if the following conditions are met:

    1. The URI matches at least one source expression in the set of source expressions obtained by parsing the source list.
    2. At least one of the following is true:
      1. The URI is one of not the result of a redirect.
      2. The set of source expressions obtained by parsing the source list contains the source expression ‘unsafe-redirect’ .
      3. The source list is the U+002A ASTERISK character ( * ).

    Note: No URIs match an empty set of source expressions, such as the set obtained by parsing the source list ‘none’ .

    4.2.2.1 Security Considerations for GUID URI schemes

    This section is not normative.

    As defined above, special URI schemes that refer to specific pieces of unique content, such as «data:», «blob:» and «filesystem:» are excluded from matching a policy of * and must be explicitly listed. Policy authors should note that the content of such URIs is often derived from a response body or execution in a Document context, which may be unsafe. Especially for the default-src and script-src directives, policy authors should be aware that allowing «data:» URIs is equivalent to unsafe-inline and allowing «blob:» or «filesystem:» URIs is equivalent to unsafe-eval .

    4.2.2.2 Path Matching

    This section is not normative.

    The rules for matching source expressions that contain paths are simpler than they look: paths that end with the ‘/’ character match all files in a directory and its subdirectories. Paths that do not end with the ‘/’ character match only one specific file. A few examples should make this clear:

    1. The source expression example.com has no path, and therefore matches any file served from that host.
    2. The source expression example.com/scripts/ matches any file in the scripts directory of example.com , and any of its subdirectories. For example, both https://example.com/scripts/file.js and https://example.com/scripts/js/file.js would match.
    3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com .
    4. Likewise, the source expression example.com/js matches only the file named js . In particular, note that it would not match files inside a directory named js . Files like example.com/js/file.js would be matched only if the source expression ended with a trailing «/», as in example.com/js/ .

    Note: Query strings have no impact on matching: the source expression example.com/file?key=value matches all of https://example.com/file , https://example.com/file?key=value , https://example.com/file?key=notvalue , and https://example.com/file?notkey=notvalue .

    4.2.2.3 Paths and Redirects

    To avoid leaking path information cross-origin (as discussed in Egor Homakov’s Using Content-Security-Policy for Evil), the matching algorithm ignores the path component of a source expression if the resource being loaded is the result of a redirect. For example, given a page with an active policy of img-src example.com not-example.com/path :

    • Directly loading https://not-example.com/not-path would fail, as it doesn’t match the policy.
    • Directly loading https://example.com/redirector would pass, as it matches example.com .
    • Assuming that https://example.com/redirector delivered a redirect response pointing to https://not-example.com/not-path , the load would succeed, as the initial URL matches example.com , and the redirect target matches not-example.com/path if we ignore its path component.

    This restriction reduces the granularity of a document’s policy when redirects are in play, which isn’t wonderful, but given that we certainly don’t want to allow brute-forcing paths after redirects, it seems a reasonable compromise.

    The relatively long thread «Remove paths from CSP?» from public-webappsec@w3.org has more detailed discussion around alternate proposals.

    4.2.3 The nonce attribute

    Nonce sources require a new attribute to be added to both script and style elements: .

    This attribute reflects the value of the element’s nonce content attribute. This attribute reflects the value of the element’s nonce content attribute.

    4.2.4 Valid Nonces

    An element has a for a set of source expressions if the value of the element’s nonce attribute after stripping leading and trailing whitespace is a case-sensitive match for the nonce-value component of at least one nonce-source expression in set of source expressions .

    4.2.5 Valid Hashes

    An is the script block’s source for script elements, or the value of the element’s textContent IDL attribute for non- script elements such as style .

    The for is the result of applying an algorithm to the element’s content.

    To determine whether element has a for a set of source expressions , execute the following steps:

    1. Let hashes be a list of all hash-source expressions in set of source expressions .
    2. For each hash in hashes :
      1. Let algorithm be:
        • SHA-256 if the hash-algo component of hash is a case-insensitive match for the string «sha256»
        • SHA-384 if the hash-algo component of hash is a case-insensitive match for the string «sha384»
        • SHA-512 if the hash-algo component of hash is a case-insensitive match for the string «sha512»
      2. Let expected be the hash-value component of hash .
      3. Let actual be the base64 encoding of the binary digest of element ’s content using the algorithm algorithm.
      4. If actual is a case-sensitive match for expected , return true and abort these steps.
    3. Return false.

    Note: If an element has an invalid hash, it would be helpful if the user agent reported the failure to the author by adding a warning message containing the actual hash value.

    4.3 Media Type List

    The plugin-types directive uses a value consisting of a .

    Each in the media type list represents a specific type of resource that can be retrieved and used to instantiate a plugin in the protected resource.

    4.3.1 Parsing

    To media type list , the user agent MUST use an algorithm equivalent to the following:

    1. Let the set of media types be the empty set.
    2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type , add the token to the set of media types . Otherwise ignore the token.
    3. Return the set of media types .

    4.3.2 Matching

    A media type if, and only if, the media type is a case-insensitive match for at least one token in the set of media types obtained by parsing the media type list.

    4.4 Reporting

    To , the user agent MUST use an algorithm equivalent to the following:

    1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data , blob , or filesystem ), then abort these steps, and return the ASCII serialization of uri ’s scheme.
    2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri ’s origin.
    3. Return uri , with any fragment component removed.

    To , the user agent MUST use an algorithm equivalent to the following:

    1. Prepare a JSON object violation with the following keys and values: blocked-uri The originally requested URI of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URI (inline script and inline style, for example). document-uri The address of the protected resource, stripped for reporting. effective-directive The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. » script-src «) even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive. original-policy The original policy, as received by the user agent. referrer The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer. status-code The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0. violated-directive The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
    2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation : The URI of the resource where the violation occurred, stripped for reporting. line-number The line number in source-file on which the violation occurred. column-number The column number in source-file on which the violation occurred.
    3. Return violation .

    Note: blocked-uri will not contain the final location of a resource that was blocked after one or more redirects. It instead will contain only the location that the protected resource requested, before any redirects were followed.

    To , the user agent MUST use an algorithm equivalent to the following:

    1. Prepare a JSON object report object with a single key, csp-report , whose value is the result of generating a violation report object.
    2. Let report body be the JSON stringification of report object .
    3. For each report URI in the set of report URIs:
      1. If the user agent has already sent a violation report for the protected resource to report URI , and that report contained an entity body that exactly matches report body , the user agent MAY abort these steps and continue to the next report URI .
      2. Queue a task to fetch report URI from the origin of the protected resource, with the synchronous flag not set, using HTTP method POST , with a Content-Type header field of application/csp-report , and an entity body consisting of report body . If the origin of report URI is not the same as the origin of the protected resource, the block cookies flag MUST also be set. The user agent MUST NOT follow redirects when fetching this resource. (Note: The user agent ignores the fetched resource.) The task source for these tasks is the .

    To , the user agent MUST:

    Note: This section of the specification should not be interpreted as limiting user agents’ ability to apply restrictions to violation reports in order to limit data leakage above and beyond what these algorithms specify.

    5 Processing Model

    To a policy, the user agent MUST parse the policy and enforce each of the directives contained in the policy, where the specific requirements for enforcing each directive are defined separately for each directive (See §7 Directives, below).

    Generally speaking, enforcing a directive prevents the protected resource from performing certain actions, such as loading scripts from URIs other than those indicated in a source list. These restrictions make it more difficult for an attacker to abuse an injection vulnerability in the resource because the attacker will be unable to usurp the resource’s privileges that have been restricted in this way.

    Note: User agents may allow users to modify or bypass policy enforcement through user preferences, bookmarklets, third-party additions to the user agent, and other such mechanisms.

    To a policy, the user agent MUST parse the policy and monitor each of the directives contained in the policy.

    Monitoring a directive does not prevent the protected resource from undertaking any actions. Instead, any actions that would have been prevented by the directives are allowed, but a violation report is generated and reported to the developer of the web application. Monitoring a policy is useful for testing whether enforcing the policy will cause the web application to malfunction.

    A server MAY cause user agents to monitor one policy while enforcing another policy by returning both Content-Security-Policy and Content-Security-Policy-Report-Only header fields. For example, if a server operator may wish to enforce one policy but experiment with a stricter policy, she can monitor the stricter policy while enforcing the original policy. Once the server operator is satisfied that the stricter policy does not break the web application, the server operator can start enforcing the stricter policy.

    If the user agent monitors or enforces a policy that does not contain any directives, the user agent SHOULD report a warning message in the developer console.

    If the user agent monitors or enforces a policy that contains an unrecognized directive, the user agent SHOULD report a warning message in the developer console indicating the name of the unrecognized directive.

    If the user agent monitors or enforces a policy that contains a directive that contains a source list, then the user agent MUST set a CSP Request Header when requesting cross-origin resources, as described in §3.4 The CSP HTTP Request Header.

    5.1 Workers

    Whenever a user agent runs a worker:

    • If the worker’s script’s origin is a globally unique identifier (for example, the worker’s script’s URL has a scheme of data , blob , or filesystem ), then:
      • If the user agent is enforcing a CSP policy for the owner document , the user agent MUST enforce the CSP policy for the worker.
      • If the user agent is monitoring a CSP policy for the owner document , the user agent MUST monitor the CSP policy for the worker.
    • Otherwise:
      • If the worker’s script is delivered with a Content-Security-Policy HTTP header containing the value policy , the user agent MUST enforce policy for the worker.
      • If the worker’s script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy , the user agent MUST monitor policy for the worker.

    5.2 srcdoc IFrames

    Whenever a user agent creates an iframe srcdoc document in a browsing context nested in the protected resource, if the user agent is enforcing any policies for the protected resource, the user agent MUST enforce those policies on the iframe srcdoc document as well.

    Whenever a user agent creates an iframe srcdoc document in a browsing context nested in the protected resource, if the user agent is monitoring any policies for the protected resource, the user agent MUST monitor those policies on the iframe srcdoc document as well.

    6 Script Interfaces

    6.1 SecurityPolicyViolationEvent Interface


    6.2 SecurityPolicyViolationEventInit Interface

    6.3 Firing Violation Events

    To , the user agent MUST use an algorithm equivalent to the following:

    1. Let report object be the result of generating a violation report object.
    2. Queue a task to fire an event named securitypolicyviolation using the SecurityPolicyViolationEvent interface with the following initializations:
      • blockedURI MUST be initialized to the value of report object ’s blocked-uri key.
      • documentURI MUST be initialized to the value of report object ’s document-uri key.
      • effectiveDirective MUST be initialized to the value of report object ’s effective-directive key.
      • originalPolicy MUST be initialized to the value of report object ’s original-policy key.
      • referrer MUST be initialized to the value of report object ’s referrer key.
      • violatedDirective MUST be initialized to the value of report object ’s violated-directive key.
      • sourceFile MUST be initialized to the value of report object ’s source-file key.
      • lineNumber MUST be initialized to the value of report object ’s line-number key.
      • columnNumber MUST be initialized to the value of report object ’s column-number key.

    7 Directives

    This section describes the content security policy directives introduced in this specification. Directive names are case insensitive.

    In order to protect against Cross-Site Scripting (XSS), web application authors SHOULD include:

    • both the script-src and object-src directives, or
    • include a default-src directive, which covers both scripts and plugins.

    In either case, authors SHOULD NOT include either ‘unsafe-inline’ or data: as valid sources in their policies. Both enable XSS attacks by allowing code to be included directly in the document itself; they are best avoided completely.

    Redirects are another area of potential concern. Authors SHOULD NOT include ‘unsafe-redirect’ as valid sources in their policies. It makes it more difficult to reason about the complete set of resources that a policy allows, especially given the path behavior outlined in the §4.2.2.3 Paths and Redirects section.

    7.1 base-uri

    The directive restricts the URIs that can be used to specify the document base URL. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Step 4 of the algorithm defined in HTML5 to obtain a document’s base URL MUST be changed to:

    1. If the previous step was not successful, or the result of the previous step does not match the allowed base URIs, then the document base URL is fallback base URL . Otherwise, it is the result of the previous step.

    7.2 child-src

    The directive governs the creation of nested browsing contexts as well as Worker execution contexts. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the child-src directive’s value as a source list if a child-src directive is explicitly specified, and otherwise to the default sources.

    7.2.1 Nested Browsing Contexts

    To enforce the child-src directive the user agent MUST enforce the frame-src directive.

    7.2.2 Workers

    Whenever the user agent fetches a URL while processing the Worker or SharedWorker constructors [WORKERS], the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation if the URI does not match the allowed child sources.

    7.3 connect-src

    The directive restricts which URIs the protected resource can load using script interfaces. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the connect-src directive’s value as a source list if the policy contains an explicit connect-src directive, or otherwise to the default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed connection targets, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Processing the send() method of an XMLHttpRequest object.
    • Processing the WebSocket constructor.
    • Processing the EventSource constructor.
    • Sending a beacon via the sendBeacon() method [BEACON]

    7.3.1 Usage

    This section is not normative.

    JavaScript offers a few mechanisms that directly connect to an external server to send or receive information. EventSource maintains an open HTTP connection to a server in order to receive push notifications, WebSockets open a bidirectional communication channel between your browser and a server, and XMLHttpRequest makes arbitrary HTTP requests on your behalf. These are powerful APIs that enable useful functionality, but also provide tempting avenues for data exfiltration.

    The connect-src directive allows you to ensure that these sorts of connections are only opened to origins you trust. Sending a policy that defines a list of source expressions for this directive is straightforward. For example, to limit connections to only example.com , send the following header:

    All of the following will fail with the preceding directive in place:

    • new WebSocket(«wss://evil.com/»);
    • (new XMLHttpRequest()).open(«GET», «https://evil.com/», true);
    • new EventSource(«https://evil.com»);

    7.4 default-src

    The directive sets a default source list for a number of directives. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Let the be the result of parsing the default-src directive’s value as a source list if a default-src directive is explicitly specified, and otherwise the U+002A ASTERISK character (*).

    To enforce the default-src directive, the user agent MUST enforce the following directives:

    If not specified explicitly in the policy, the directives listed above will use the default sources as their source list.

    7.4.1 Usage

    This section is not normative.

    default-src , as the name implies, serves as a default source list which the other source list-style directives will use as a fallback if they’re not otherwise explicitly set. That is, consider the following policy declaration:

    Under this policy, fonts, frames, images, media, objects, scripts, and styles will all only load from the same origin as the protected resource, and connections will only be made to the same origin. Adding a more specific declaration to the policy would completely override the default source list for that resource type.

    Under this new policy, fonts, frames, and etc. continue to be load from the same origin, but scripts will only load from example.com . There’s no inheritance; the script-src directive sets the allowed sources of script, and the default list is not used for that resource type.

    Given this behavior, one good way of building a policy for a site would be to begin with a default-src of ‘none’ , and to build up a policy from there that contains only those resource types which are actually in use for the page you’d like to protect. If you don’t use webfonts, for instance, there’s no reason to specify a source list for font-src ; specifying only those resource types a page uses ensures that the possible attack surface for that page remains as small as possible.

    7.5 font-src

    The directive restricts from where the protected resource can load fonts. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the font-src directive’s value as a source list if the policy contains an explicit font-src , or otherwise to the default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed font sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for display in a font, such as when processing the Cascading Style Sheets (CSS) rule.

    7.6 form-action

    The restricts which URIs can be used as the action of HTML form elements. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed form actions, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Processing an HTML form element.
    • Pinging an endpoint during hyperlink auditing

    Note: form-action does not fall back to the default sources when the directive is not defined. That is, a policy that defines default-src ‘none’ but not form-action will still allow form submissions to any target.

    7.7 frame-ancestors

    The directive indicates whether the user agent should allow embedding the resource using a frame , iframe , object , embed or applet tag, or equivalent functionality in non-HTML resources. Resources can use this directive to avoid many UI Redressing [UIREDRESS] attacks by avoiding being embedded into potentially hostile contexts.

    The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the frame-ancestors directive’s value as a source list. If a frame-ancestors directive is not explicitly included in the policy, then allowed frame ancestors is » * «.

    To enforce the frame-ancestors directive, whenever the user agent would load the protected resource into a nested browsing context, the user agent MUST perform the following steps:

    1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
    2. Let ancestorList be the list of all ancestors of nestedContext .
    3. For each ancestorContext in ancestorList :
      1. Let document be ancestorContext ’s active document.
      2. If document ’s URL does not match the allowed frame ancestors, the user agent MUST:
        1. Abort loading the protected resource.
        2. Act as if it received an empty HTTP 200 response.
        3. Parse a sandboxing directive using the empty string as the input and the newly created document’s forced sandboxing flag set as the output.

    Steps 2.2 and 2.3 ensure that the blocked frame appears to be a normal cross-origin document’s load. If these steps are ignored, leakage of a document’s policy state is possible. The user agent MAY implement these steps by instead redirecting the user to friendly error page in a unique origin which provides the option of opening the blocked page in a new top-level browsing context.

    The frame-ancestors directive MUST be ignored when monitoring a policy, and when a contained in a policy defined via a meta element.

    Note: frame-ancestors does not fall back to the default sources when the directive is not defined. That is, a policy that defines default-src ‘none’ but not frame-ancestors will still allow the resource to be framed from anywhere.

    When generating a violation report for a frame-ancestors violation, the user agent MUST NOT include the value of the embedding ancestor as a blocked-uri value unless it is same-origin with the protected resource, as disclosing the value of cross-origin ancestors is a violation of the Same-Origin Policy.

    7.7.1 Relation to X-Frame-Options

    This directive is similar to the X-Frame-Options header that several user agents have implemented. The ‘none’ source expression is roughly equivalent to that header’s DENY , ‘self’ to SAMEORIGIN , and so on. The major difference is that many user agents implement SAMEORIGIN such that it only matches against the top-level document’s location. This directive checks each ancestor. If any ancestor doesn’t match, the load is cancelled. [RFC7034]

    The frame-ancestors directive obsoletes the X-Frame-Options header. If a resource has both policies, the frame-ancestors policy SHOULD be enforced and the X-Frame-Options policy SHOULD be ignored.

    7.7.2 Multiple Host Source Values

    This section is not normative.

    Multiple source-list expressions are allowed in a single policy (in contrast to X-Frame-Options , which allows only one) to enable scenarios involving embedded application components that are multiple levels below the top-level browsing context.

    Many common scenarios for permissioned embedding (e.g. embeddable payment, sharing or social apps) involve potentially many hundreds or thousands of valid source-list expressions, but it is strongly recommended against accommodating such scenarios with a static frame-ancestors directive listing multiple values. In such cases it is beneficial to generate this value dynamically, based on an HTTP Referer header or an explicitly passed-in value, to allow only the sources necessary for each given embedding of the resource.

    Consider a service providing a payments application at https://payments/makeEmbedded . The service allows this resource to be embedded by both merchant Alice and merchant Bob, who compete with each other. Sending:

    would allow Bob to re-frame Alice’s resource and create fraudulent clicks, perhaps discrediting Alice with her customers or the payments service. If the payments service used additional information (e.g. as part of a URL like https://payments/makeEmbedded?merchant=alice ) to send individually-tailored headers listing only the source-list expressions needed by each merchant, this attack would be eliminated.

    7.8 frame-src

    The directive is deprecated. Authors who wish to govern nested browsing contexts SHOULD use the child-src directive instead.

    The frame-src directive restricts from where the protected resource can embed frames. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the frame-src directive’s value as a source list if the policy contains an explicit frame-src , or otherwise to the list of allowed child sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed frame sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for display in a nested browsing context in the protected resource created by an iframe or a frame element.
    • Navigated such a nested browsing context.

    7.9 img-src

    The directive restricts from where the protected resource can load images. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the img-src directive’s value as a source list if the policy contains an explicit img-src , or otherwise to the list of default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed image sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for an image, such as when processing the src or srcset attributes of an img element, the src attribute of an input element with a type of image , the poster attribute of a video element, the url() , or values on any Cascading Style Sheets (CSS) property that is capable of loading an image [CSS4-IMAGES], or the href attribute of a link element with an image-related rel attribute, such as icon .

    7.10 media-src

    The directive restricts from where the protected resource can load video, audio, and associated text tracks. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the media-src directive’s value as a source list if the policy contains an explicit media-src , or otherwise to the list of default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed media sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for a video or audio clip, such as when processing the src attribute of a video , audio , source , or track elements.

    7.11 object-src

    The directive restricts from where the protected resource can load plugins. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the object-src directive’s value as a source list if the policy contains an explicit object-src , or otherwise to the list of default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed object sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for a plugin, such as when processing the data attribute of an object element, the src attribute of an embed elements, or the code or archive attributes of an applet element.
    • Requesting data for display in a nested browsing context in the protected resource created by an object or an embed element.
    • Navigating such a nested browsing context.

    It is not required that the consumer of the element’s data be a plugin in order for the object-src directive to be enforced. Data for any object , embed , or applet element MUST match the allowed object sources in order to be fetched. This is true even when the element data is semantically equivalent to content which would otherwise be restricted by one of the other directives, such as an object element with a text/html MIME type.

    Whenever the user agent would load a plugin without an associated URI (e.g., because the object element lacked a data attribute), if the protected resource’s URI does not match the allowed object sources, the user agent MUST NOT load the plugin.

    7.12 plugin-types

    The directive restricts the set of plugins that can be invoked by the protected resource by limiting the types of resources that can be embedded. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Whenever the user agent would instantiate a plugin to handle resource while enforcing the plugin-types directive, the user agent MUST instead act as though the plugin reported an error and report a violation if any of the following conditions hold:

    • The plugin is embedded into the protected resource via an object or embed element that does not explicitly declare a MIME type via a type attribute.
    • resource ’s media type does not match the list of allowed plugin media types.
    • The plugin is embedded into the protected resource via an object or embed element, and the media type declared in the element’s type attribute is not a case-insensitive match for the resource ’s media type.
    • The plugin is embedded into the protected resource via an applet element, and resource ’s media type is not a case-insensitive match for application/x-java-applet .

    Note: In any of these cases, acting as though the plugin reported an error will cause the user agent to display the fallback content.

    Whenever the user agent creates a plugin document in a nested browsing context in the protected resource, if the user agent is enforcing any plugin-types directives for the protected resource, the user agent MUST enforce those plugin-types directives on the plugin document as well.


    Whenever the user agent creates a plugin document in a nested browsing context in the protected resource, if the user agent is monitoring any plugin-types directives for the protected resource, the user agent MUST monitor those plugin-types directives on the plugin document as well.

    7.12.1 Usage

    This section is not normative.

    The plugin-types directive whitelists a certain set of MIME types that can be embedded in a protected resource. For example, a site might want to ensure that PDF content loads, but that no other plugins can be instantiated. The following directive would satisfy that requirement:

    Resources embedded via an embed or object element delivered with an application/pdf content type would be rendered in the appropriate plugin; resources delivered with some other content type would be blocked. Multiple types can be specified, in any order. If the site decided to additionally allow Flash at some point in the future, it could do so with the following directive:

    Note: Wildcards are not accepted in the plugin-types directive. Only the resource types explicitly listed in the directive will be allowed.

    7.12.2 Predeclaration of expected media types

    This section is not normative.

    Enforcing the plugin-types directive requires that object and embed elements declare the expected media type of the resource they include via the type attribute. If an author expects to load a PDF, she could specify this as follows:

    If resource isn’t actually a PDF file, it won’t load. This prevents certain types of attacks that rely on serving content that unexpectedly invokes a plugin other than that which the author intended.

    Note: resource will not load in this scenario even if its media type is otherwise whitelisted: resources will only load when their media type is whitelisted and matches the declared type in their containing element.

    7.13 referrer

    The directive specifies the referrer policy [REFERRER] that the user agent applies when determining what referrer information should be included with requests made, and with browsing contexts created from the context of the protected resource. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Note: The directive name does not share the HTTP header’s misspelling.

    When enforcing the referrer directive, the user agent MUST execute [REFERRER]’s Set environment ’s referrer policy to policy . algorithm on the protected resource’s JavaScript global environment using the result of executing the Determine token ’s Policy algorithm on the referrer directive’s value.

    7.13.1 Usage

    This section is not normative.

    A protected resource can prevent referrer leakage by specifying no-referrer as the value of its policy’s referrer directive:

    This will cause all requests made from the protected resource’s context to have an empty Referer [sic] header.

    7.14 reflected-xss

    The directive instructs a user agent to activate or deactivate any heuristics used to filter or block reflected cross-site scripting attacks. The syntax for the name and value of the directive are described by the following ABNF grammar:

    A user agent with support for XSS protection MUST enforce this directive as follows:

    • If the value of the directive is allow , the user agent MUST disable its active protections against reflected cross-site scripting attacks for the protected resource.
    • If the value of the directive is filter , the user agent MUST enable its active protections against reflected cross-site scripting attacks for the protected resource. This might result in filtering script that is believed to be reflected being filtered or selectively blocking script execution.
    • If the value of the directive is block , the user agent MUST stop rendering the protected resource upon detection of reflected script, and instead act as if there was a fatal network error and no resource was obtained, andreport a violation:

    If the user agent’s active protections against reflected cross-site scripting attacks detect or prevent script execution, the user agent MUST report a violation.

    Note: The reflected-xss directive will be ignored if contained within a meta element.

    7.14.1 Relationship to X-XSS-Protection

    This directive is meant to subsume the functionality provided by the proprietary X-XSS-Protection HTTP header which is supported by a number of user agents. Roughly speaking:

    • reflected-xss allow is equivalent to X-XSS-Protection: 0
    • reflected-xss filter is equivalent to X-XSS-Protection: 1
    • reflected-xss block is equivalent to X-XSS-Protection: 1; mode=block

    7.15 report-uri

    The directive specifies a URI to which the user agent sends reports about policy violation. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The is the value of the report-uri directive, each resolved relative to the protected resource’s URI.

    The process of sending violation reports to the URIs specified in this directive’s value is defined in this document’s §4.4 Reporting section.

    Note: The report-uri directive will be ignored if contained within a meta element.

    7.16 sandbox

    The directive specifies an HTML sandbox policy that the user agent applies to the protected resource. The syntax for the name and value of the directive are described by the following ABNF grammar:

    When enforcing the sandbox directive, the user agent MUST parse a sandboxing directive using the directive-value as the input and protected resource’s forced sandboxing flag set as the output. [HTML5]

    Note: The sandbox directive will be ignored when monitoring a policy, and when contained in a policy defined via a meta element.

    7.16.1 Usage

    This section is not normative.

    HTML5 defines a sandbox attribute for iframe elements, intended to allow web authors to reduce the risk of including potentially untrusted content by imposing restrictions on that content’s abilities. When the attribute is set, the content is forced into a unique origin, prevented from submitting forms, running script, creating or navigating other browsing contexts, and prevented from running plugins. These restrictions can be loosened by setting certain flags as the attribute’s value.

    The sandbox directive allows any resource, framed or not, to ask for the same sorts of restrictions to be applied to itself.

    For example, a message board or email system might provide downloads of arbitrary attachments provided by other users. Attacks that rely on tricking a client into rendering one of these attachments could be mitigated by requesting that resources only be rendered in a very restrictive sandbox. Sending the sandbox directive with an empty value establishes such an environment:

    More trusted resources might be allowed to run in an environment with fewer restrictions by adding allow-* flags to the directive’s value. For example, you can allow a page that you trust to run script, while ensuring that it isn’t treated as same-origin with the rest of your site. This can be accomplished by sending the sandbox directive with the allow-scripts flag:

    The set of flags available to the CSP directive should match those available to the iframe attribute. Currently, those include:

    Note: Like the rest of Content Security Policy, the sandbox directive is meant as a defense-in-depth. Web authors would be well-served to use it in addition to standard sniffing-mitigation and privilege-reduction techniques.

    7.17 script-src

    The directive restricts which scripts the protected resource can execute. The directive also controls other resources, such as XSLT style sheets [XSLT], which can cause the user agent to execute script. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the script-src directive’s value as a source list if the policy contains an explicit script-src , or otherwise to the default sources.

    If ‘unsafe-inline’ is not in the list of allowed script sources, or if at least one nonce-source or hash-source is present in the list of allowed script sources:

    • Whenever the user agent would execute an inline script from a script element that lacks a valid nonceand lacks a valid hash for the allowed script sources, instead the user agent MUST NOT execute script, and MUST report a violation.
    • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
    • Whenever the user agent would execute script contained in a javascript URI, instead the user agent MUST NOT execute the script, and MUST report a violation.

    If ‘unsafe-eval’ is not in allowed script sources:

    • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw an EvalError exception.
    • When called as a constructor, the function Function [ECMA-262] MUST throw an EvalError exception.
    • When called with a first argument that is not callable (a string, for example), the setTimeout() function MUST return zero without creating a timer.
    • When called with a first argument that is not callable (a string, for example), the setInterval() function MUST return zero without creating a timer.

    Whenever the user agent fetches a URI (including when following redirects) in the course of one of the following activities, if the URI does not match the allowed script sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
    • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WORKERS]
    • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import . [HTML-IMPORTS]
    • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the processing directive in an XML document [XML11], the href attributes on and elements.

    7.17.1 Nonce usage for script elements

    This section is not normative.

    The script-src directive lets developers specify exactly which script elements on a page were intentionally included for execution. Ideally, developers would avoid inline script entirely and whitelist scripts by URL. However, in some cases, removing inline scripts can be difficult or impossible. For those cases, developers can whitelist scripts using a randomly generated nonce.

    Usage is straightforward. For each request, the server generates a unique value at random, and includes it in the Content-Security-Policy header:

    This same value is then applied as a nonce attribute to each script element that ought to be executed. For example, if the server generated the random value Nc3n83cnSAd3wc3Sasdfn939hc3 , the server would send the following policy:

    Script elements can then execute either because their src URLs are whitelisted or because they have a valid nonce:

    Note that the nonce’s value is not a hash or signature that verifies the contents of the script resources. It’s quite simply a random string that informs the user agent which scripts were intentionally included in the page.

    Script elements with the proper nonce execute, regardless of whether they’re inline or external. Script elements without the proper nonce don’t execute unless their URLs are whitelisted. Even if an attacker is able to inject markup into the protected resource, the attack will be blocked by the attacker’s inability to guess the random value.

    7.17.2 Hash usage for script elements

    This section is not normative.

    The script-src directive lets developers whitelist a particular inline script by specifying its hash as an allowed source of script.

    Usage is straightforward. The server computes the hash of a particular script block’s contents, and includes the base64 encoding of that value in the Content-Security-Policy header:

    Each inline script block’s contents are hashed, and compared against the whitelisted value. If there’s a match, the script is executed. For example, the SHA-256 digest of alert(‘Hello, world.’); is YWIzOWNiNzJjNDRlYzc4MTgwMDhmZDlkOWI0NTAyMjgyY2MyMWJlMWUyNjc1ODJlYWJhNjU5MGU4NmZmNGU3OAo= . If the server sent the following header:

    Then the following script tag would result in script execution:

    Whitespace is significant. The following scripts blocks would not hash to the same value, and would therefore not execute:

    Note also that the hash applies only to inline script. An externalized script containing the value alert(‘Hello, world.’); would not execute if its origin was not whitelisted as a valid source of script.

    7.18 style-src

    The directive restricts which styles the user may applies to the protected resource. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the style-src directive’s value as a source list if the policy contains an explicit style-src , or otherwise to the default sources.

    If ‘unsafe-inline’ is not in the list of allowed style sources, or if at least one nonce-source or hash-source is present in the list of allowed style sources:

    • Whenever the user agent would apply style from a style element that lacks a valid nonceand lacks a valid hash for the allowed style sources, instead the user agent MUST ignore the style, and MUST report a violation.
    • Whenever the user agent would apply style from a style attribute, instead the user agent MUST ignore the style, and MUST report a violation.

    Note: These restrictions on inline do not prevent the user agent from applying style from an external stylesheet (e.g., found via
    ).

    If ‘unsafe-eval’ is not in allowed style sources, then:

    • Whenever the user agent would invoke the Cascading Style Sheets Object Model algorithms insert a CSS rule, parse a CSS rule, parse a CSS declaration block, or parse a group of selectors instead the user agent MUST throw a SecurityError exception and terminate the algorithm. This would include, for example, all invocations of CSSOM’s various cssText setters and insertRule methods. [CSSOM][HTML5]

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed style sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting external style sheets, such as when processing the href attribute of a link element with a rel attribute containing the token stylesheet or when processing the directive in a stylesheet.

    Note: The style-src directive does not restrict the use of XSLT. XSLT is restricted by the script-src directive because the security consequences of including an untrusted XSLT stylesheet are similar to those incurred by including an untrusted script.

    7.18.1 Nonce usage for style elements

    This section is not normative.

    See the script-src nonce usage information for detail; the application of nonces to style elements is similar enough to avoid repetition here.

    7.18.2 Hash usage for style elements

    This section is not normative.

    See the script-src hash usage information for detail; the application of hashes to style elements is similar enough to avoid repetition here.

    8 Examples

    8.1 Sample Policy Definitions

    This section provides some sample use cases and supporting policies.

    This policy allows inline content (such as inline script elements), use of eval , and loading resources over https . Note: This policy does not provide any protection from cross-site scripting vulnerabilities.

    The inline script elements would then only execute if they contained a matching nonce attribute:

    8.2 Sample Violation Report

    This section contains an example violation report the user agent might sent to a server when the protected resource violations a sample policy.

    In the following example, the user agent rendered a representation of the resource http://example.org/page.html with the following policy:

    The protected resource loaded an image from http://evil.example.com/image.png , violating the policy.

    9 Security Considerations

    9.1 Cascading Style Sheet (CSS) Parsing

    The style-src directive restricts the locations from which the protected resource can load styles. However, if the user agent uses a lax CSS parsing algorithm, an attacker might be able to trick the user agent into accepting malicious «stylesheets» hosted by an otherwise trustworthy origin.

    These attacks are similar to the CSS cross-origin data leakage attack described by Chris Evans in 2009. User agents SHOULD defend against both attacks using the same mechanism: stricter CSS parsing rules for style sheets with improper MIME types.

    9.2 Violation Reports

    The violation reporting mechanism in this document has been designed to mitigate the risk that a malicious web site could use violation reports to probe the behavior of other servers. For example, consider a malicious web site that white lists https://example.com as a source of images. If the malicious site attempts to load https://example.com/login as an image, and the example.com server redirects to an identity provider (e.g., idenityprovider.example.net ), CSP will block the request. If violation reports contained the full blocked URI, the violation report might contain sensitive information contained in the redirected URI, such as session identifiers or purported identities. For this reason, the user agent includes only the origin of the blocked URI.

    10 Implementation Considerations

    The Content-Security-Policy header is an end-to-end header. It is processed and enforced at the client and, therefore, SHOULD NOT be modified or removed by proxies or other intermediaries not in the same administrative domain as the resource.

    The originating administrative domain for a resource might wish to apply a Content-Security-Policy header outside of the immediate context of an application. For example, a large organization might have many resources and applications managed by different individuals or teams but all subject to a uniform organizational standard. In such situations, a Content-Security-Policy header might be added or combined with an existing one at a network-edge security gateway device or web application firewall. To enforce multiple policies, the administrator SHOULD combine the policy into a single header. An administrator might wish to use different combination algorithms depending on his or her intended semantics.

    One sensible policy combination algorithm is to start by allowing a default set of sources and then letting individual upstream resource owners expand the set of allowed sources by including additional origins. In this approach, the resultant policy is the union of all allowed origins in the input policies.

    Another sensible policy combination algorithm is to intersect the given policies. This approach enforces that content comes from a certain whitelist of origins, for example, preventing developers from including third-party scripts or content in violation of organizational standards and practices. In this approach, the combination algorithm forms the combined policy by removing disallowed hosts from the policies supplied by upstream resource owners.

    Interactions between the default-src and other directives SHOULD be given special consideration when combining policies. If none of the policies contains a default-src directive, adding new src directives results in a more restrictive policy. However, if one or more of the input policies contain a default-src directive, adding new src directives might result in a less restrictive policy, for example, if the more specific directive contains a more permissive set of allowed origins.

    Using a more restrictive policy than the input policy authored by the resource owner might prevent the resource from rendering or operating as intended.


    Note also that migration to HTTPS from HTTP may require updates to the policy in order to keep things running as before. Source expressions like http://example.com do not match HTTPS resources. For example, administrators SHOULD carefully examine existing policies before rolling out HTTP Strict Transport Security headers for an application. [RFC6797]

    11 IANA Considerations

    The permanent message header field registry should be updated with the following registrations: [RFC3864]

    11.1 Content-Security-Policy

    11.2 Content-Security-Policy-Report-Only

    11.3 CSP

    12 Acknowledgements

    In addition to the documents in the W3C Web Application Security working group, the work on this document is also informed by the work of the IETF websec working group, particularly that working group’s requirements document: draft-hodges-websec-framework-reqs.

    A portion of the frame-ancestors directive was originally developed as X-Frame-Options . [RFC7034]

    Conformance

    Document conventions

    Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words «MUST», «MUST NOT», «REQUIRED», «SHALL», «SHALL NOT», «SHOULD», «SHOULD NOT», «RECOMMENDED», «MAY», and «OPTIONAL» in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

    All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

    Examples in this specification are introduced with the words «for example» or are set apart from the normative text with , like this:

    This is an example of an informative example.

    Informative notes begin with the word «Note» and are set apart from the normative text with , like this:

    Note, this is an informative note.

    Conformant Algorithms

    Requirements phrased in the imperative as part of algorithms (such as «strip any leading space characters» or «return false and abort these steps») are to be interpreted with the meaning of the key word («must», «should», «may», etc) used in introducing the algorithm.

    Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

    Conformance Classes

    A must implement all the requirements listed in this specification that are applicable to user agents.

    A must implement all the requirements listed in this specification that are applicable to servers.

    Content Security Policy

    W3C Cand > 3 September 2014

    Abstract

    This document defines a policy language used to declare a set of content restrictions for a web resource, and a mechanism for transmitting the policy from a server to a client where the policy is enforced.

    Status of this document

    This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

    This document was published by the Web Application Security Working Group as a Candidate Recommendation. This document is intended to become a W3C Recommendation.

    The (archived) public mailing list public-webappsec@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “CSP2” in the subject, preferably like this: “[CSP2] …summary of comment…

    Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

    The entrance criteria for this document to enter the Proposed Recommendation stage is to have a minimum of two independent and interoperable user agents that implementation all the features of this specification, which will be determined by passing the user agent tests defined in the test suite developed by the Working Group.

    This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An indiv > This document is governed by the 1 August 2014 W3C Process Document.

    The following features are at-risk, and may be dropped during the CR period:

    • §3.4 The CSP HTTP Request Header
    • §7.2 child-src

    Table of Contents

    1 Introduction

    This section is not normative.

    This document defines Content Security Policy, a mechanism web applications can use to mitigate a broad class of content injection vulnerabilities, such as cross-site scripting (XSS). Content Security Policy is a declarative policy that lets the authors (or server administrators) of a web application inform the client about the sources from which the application expects to load resources.

    To mitigate XSS attacks, for example, a web application can declare that it only expects to load script from specific, trusted sources. This declaration allows the client to detect and block malicious scripts injected into the application by an attacker.

    Content Security Policy (CSP) is not intended as a first line of defense against content injection vulnerabilities. Instead, CSP is best used as defense-in-depth, to reduce the harm caused by content injection attacks. As a first line of defense against content injection, server operators should validate their input and encode their output.

    There is often a non-trivial amount of work required to apply CSP to an existing web application. To reap the greatest benefit, authors will need to move all inline script and style out-of-line, for example into external scripts, because the user agent cannot determine whether an inline script was injected by an attacker.

    To take advantage of CSP, a web application opts into using CSP by supplying a Content-Security-Policy HTTP header. Such policies apply to the current resource representation only. To supply a policy for an entire site, the server needs to supply a policy with each resource representation.

    1.1 Changes from 1.0

    This document describes an evolution of the Content Security Policy specification. Level 2 makes two breaking changes, and adds support for a number of new directives and capabilities which are summarized below:

      The following changes are backwards incompatible with the majority of user agent’s implementations of CSP 1:

        The path component of a source expression is now ignored if the resource being loaded is the result of a redirect, as described in §4.2.2.3 Paths and Redirects.

      Note: Paths are technically new in CSP2, but they were already implemented in many user agents before this revision of CSP was completed, so noting the change here seems reasonable.

    1. Redirects are blocked by default, and explicitly allowed with a new unsafe-redirect expression.
    2. A protected resource’s ability to load Workers is now controlled via child-src rather than script-src .
    3. Workers now have their own policy, separate from the protected resource which loaded them. This is described in §5.1 Workers.
  • The following directives are brand new in this revision:
    1. base-uri controls the protected resource’s ability to specify the document base URL.
    2. child-src deprecates and replaces frame-src , controlling the protected resource’s ability to embed frames, and to load Workers.
    3. form-action controls the protected resource’s ability to submit forms.
    4. frame-ancestors controls the protected resource’s ability be embedded in other documents. It is meant to supplant the X-Frame-Options HTTP request header.
    5. plugin-types controls the protected resource’s ability to load specific types of plugins.
    6. referrer controls the protected resource’s referrer policy [REFERRER].
    7. reflected-xss controls the user agent’s built-in heuristics to actively protect against XSS. It is meant to supplant the X-XSS-Protection HTTP request header.
  • Individual inline scripts and stylesheets may be whitelisted via nonces (as described in §4.2.4 Valid Nonces) and hashes (as described in §4.2.5 Valid Hashes).
  • A CSP request header is now sent with relevant requests, as described in §3.4 The CSP HTTP Request Header.
  • A SecurityPolicyViolationEvent is fired upon violations, as described in §6.3 Firing Violation Events.
  • A number of new fields were added to violation reports (both those POSTED via report-uri , and those handed to the DOM via SecurityPolicyViolationEvent events. These include effectiveDirective , statusCode , sourceFile , lineNumber , columnNumber .
  • 2 Key Concepts and Terminology

    This section defines several terms used throughout the document.

    The term refers to either:

    1. a set of security preferences for restrictions within which the content can operate, or
    2. a fragment of text that codifies these preferences.

    The security policies defined by this document are applied by a user agent on a per-resource representation basis. Specifically, when a user agent receives a policy along with the representation of a given resource, that policy applies to that resource representation only. This document often refers to that resource representation as the .

    A is a portion of a policy that declares the specific set of restrictions for a particular resource type, or which manipulates a specific aspect of a protected resource’s configuration. A server transmits its security policy for a particular protected resource as a collection of directives, such as default-src ‘self’ , each of which declares a specific set of restrictions for that resource as instantiated by the user agent. More details are provided in the §7 Directives section.

    A directive consists of a , which indicates the privileges controlled by the directive, and a , which specifies the restrictions the policy imposes on those privileges.

    The term is defined in the Origin specification. [RFC6454]

    The term is defined in section 4 of the Origin specification. Note that URLs that do not use hierarchical elements as naming authorities have origins which are globally unique identifiers. [RFC6454]

    The term is defined in the URI specification. [URI]

    The term is defined Section 3 of HTTP/1.1 — Semantics and Content [RFC7231]

    The terms and are defined in the JSON specification. [RFC4627]

    The applet , audio , embed , iframe , img , link , object , script , source , track , and video elements are defined in the HTML5 specification. [HTML5]

    A plugin is defined in the HTML5 specification. [HTML5]

    The Cascading Style Sheets (CSS) rule is defined in the CSS Fonts Module Level 3 specification. [CSS3-FONTS]

    The XMLHttpRequest object is defined in the XMLHttpRequest specification. [XMLHTTPREQUEST]

    The WebSocket object is defined in the WebSocket specification. [WEBSOCKETS]

    The EventSource object is defined in the EventSource specification. [EVENTSOURCE]

    The Augmented Backus-Naur Form (ABNF) notation used in this document is specified in RFC5234. [ABNF]

    This document also uses the ABNF extension «#rule» as defined in Section 7 of HTTP/1.1 — Message Syntax and Routing. [RFC7230]

    The following core rules are included by reference, as defined in Appendix B.1 of [ABNF]: ALPHA (letters), DIGIT (decimal 0-9), WSP (white space) and VCHAR (printing characters).

    , , and are the digest algorithms defined by the NIST.

    The term refers to an object whose interface has one or more as defined in the Web IDL specification [WEBIDL].

    An is defined in Section 6.3.1 of HTTP/1.1 — Semantics and Content [RFC7231]

    3 Policy Delivery

    The server delivers the policy to the user agent via an HTTP response header or an HTML meta element. Servers are informed that requests are subject to a policy via an HTTP request header.

    3.1 Content-Security-Policy Header Field

    The header field is the preferred mechanism for delivering a policy.

    A server MAY send more than one HTTP header field named Content-Security-Policy with a given resource representation.

    A server MAY send different Content-Security-Policy header field values with different representations of the same resource or with different resources.

    Upon receiving an HTTP response containing at least one Content-Security-Policy header field, the user agent MUST enforce each of the policies contained in each such header field.

    3.2 Content-Security-Policy-Report-Only Header Field

    The header field lets servers experiment with policies by monitoring (rather than enforcing) a policy.

    For example, server operators might wish to develop their security policy iteratively. The operators can deploy a report-only policy based on their best estimate of how their site behaves:

    If their site violates this policy the user agent will send violation reports to the URI specified in the policy’s report-uri directive, but allow the violating resources to load regardless. Once a site has confidence that the policy is appropriate, they can start enforcing the policy using the Content-Security-Policy header field.

    A server MAY send more than one HTTP header field named Content-Security-Policy-Report-Only with a given resource representation.

    A server MAY send different Content-Security-Policy-Report-Only header field values with different representations of the same resource or with different resources.

    Upon receiving an HTTP response containing at least one Content-Security-Policy-Report-Only header field, the user agent MUST monitor each of the policies contained in each such header field.

    Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element.

    3.3 HTML meta Element

    The server MAY supply a policy in an HTML meta element with an http-equiv attribute that is a case insensitive match for the string » Content-Security-Policy «. For example:

    Add the following entry to the pragma directives for the meta element: Content security policy ( http-equiv=»content-security-policy» )

    1. If the Document’s head element is not an ancestor of the meta element, abort these steps.
    2. If the meta element lacks a content attribute, abort these steps.
    3. Let policy be the value of the content attribute of the meta element.
    4. Let directive-set be the result of parsing policy .
    5. Remove all occurrences of reflected-xss , report-uri , and sandbox directives from directive-set .
    6. Enforce each of the directives in directive-set , as defined for each directive type.

    Authors are strongly encouraged to place the meta element as early in the document as possible to reduce the risk of content injection before a protective policy can be read and enforced.

    Note: A policy specified via a meta element will be enforced along with any other policies active for the protected resource, regardless of where they’re specified. The general mechanism for determining the effect of enforcing multiple policies is detailed in the §3.5 Enforcing multiple policies. section.

    Note: Modifications to the content attribute of a meta element after the element has been parsed will be ignored.

    Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element.

    3.4 The CSP HTTP Request Header

    The header field indicates that a particular request is subject to a policy, and its value is defined by the following ABNF grammar:

    If the user agent is monitoring or enforcing a policy that includes directives whose value is a source list, and whose source list contains the ‘unsafe-redirect’ source expression, then the user agent MUST send a header field named CSP along with requests for resources whose origin does not match the protected resource’s origin. The value of this header MUST be active .

    The user agent MAY choose to send this header only if the request is for a resource type which the active policy would effect. That is, given a policy of img-src example.com ‘unsafe-redirect’ , the user agent would send CSP: active along with requests for images, but might choose not to send the header with requests for script.

    Note: The central reason for including this header is that it hints to a server that information about redirects might be leaked as a side-effect of a page’s active policy. If this header is present, a server might decline to redirect a logged-out user from example.com to accounts.example.com , for example, as a malicious embedder might otherwise be able to determine the user’s logged-in status.

    3.5 Enforcing multiple policies.

    This section is not normative.


    The above sections note that when multiple policies are present, each must be enforced or reported, according to its type. An example will help clarify how that ought to work in practice. The behavior of an XMLHttpRequest might seem unclear given a site that, for whatever reason, delivered the following HTTP headers:

    Is a connection to example.com allowed or not? The short answer is that the connection is not allowed. Enforcing both policies means that a potential connection would have to pass through both unscathed. Even though the second policy would allow this connection, the first policy contains connect-src ‘none’ , so its enforcement blocks the connection. The impact is that adding additional policies to the list of policies to enforce can only further restrict the capabilities of the protected resource.

    To demonstrate that further, consider a script tag on this page. The first policy would lock scripts down to ‘self’ , http://example.com and http://example.net via the default-src directive. The second, however, would only allow script from http://example.com/ . Script will only load if it meets both policy’s criteria: in this case, the only origin that can match is http://example.com , as both policies allow it.

    3.6 Policy applicability

    This section is not normative.

    Policies are associated with an protected resource, and enforced or monitored for that resource. If a resource does not create a new execution context (for example, when including a script, image, or stylesheet into a document), then any policies delivered with that resource are discarded without effect. Its execution is subject to the policy or policies of the including context. The following table outlines examples of these relationships:

    Resource Type What policy applies?
    Top-level Contexts HTML as a new, top-level browsing context The policy delivered with the resource
    SVG, as a top-level document Policy delivered with the resource
    Embedded Contexts Any resource included via iframe, object, or embed The policy of the embedding resource controls what may be embedded. The embedded resource, however, is controlled by the policy delivered with the resource, or the policy of the embedding resource if the embedded resource is a globally unique identifier (or a srcdoc frame).
    SVG, as an embedded document The policy delivered with the resource, or policy of the creating context if created from a globally unique identifier.
    JavaScript, as a Worker, Shared Worker or Service Worker The policy delivered with the resource, or policy of the creating context if created from a globally unique identifier
    Subresources SVG, inlined via svg Policy of the including context
    SVG, as a resource document Policy of the including context
    HTML via XMLHttpRequest Policy of the context that performed the fetch
    Image via img element Policy of the including context
    JavaScript via a script element Policy of the including context
    SVG, via img No policy; should be just as safe as JPG
    SVG, as a WebFont No policy; should be just as safe as WOFF

    4 Syntax and Algorithms

    4.1 Policy Syntax

    A Content Security Policy consists of a U+003B SEMICOLON ( ; ) delimited list of directives. Each directive consists of a directive name and (optionally) a directive value, defined by the following ABNF:

    4.1.1 Parsing Policies

    To policy , the user agent MUST use an algorithm equivalent to the following:

    1. Let the set of directives be the empty set.
    2. For each non-empty token returned by strictly splitting the string policy on the character U+003B SEMICOLON ( ; ):
      1. Skip whitespace.
      2. Collect a sequence of characters that are not space characters. The collected characters are the directive name .
      3. If there are characters remaining in token , skip ahead exactly one character (which must be a space character).
      4. The remaining characters in token (if any) are the directive value .
      5. If the set of directives already contains a directive whose name is a case insensitive match for directive name , ignore this instance of the directive and continue to the next token.
      6. Add a directive to the set of directives with name directive name and value directive value .
    3. Return the set of directives .

    4.2 Source List Syntax

    Many CSP directives use a value consisting of a , defined in the ABNF grammar below.

    Each in the source list represents a location from which content of the specified type can be retrieved. For example, the source expression ‘none’ represents the empty set of URIs, and the source expression ‘unsafe-inline’ represents content supplied inline in the resource itself.

    If the policy contains a nonce-source expression, the server MUST generate a fresh value for the nonce-value directive at random and independently each time it transmits a policy. This requirement ensures that the nonce-value is difficult for an attacker to predict.

    The host-char production intentionally contains only ASCII characters; internationalized domain names cannot be entered directly into a policy string, but instead MUST be Punycode-encoded [RFC3492]. For example, the domain üüüüüü.de would be encoded as xn--tdaaaaaa.de .

    4.2.1 Parsing Source Lists

    To source list , the user agent MUST use an algorithm equivalent to the following:

    1. Strip leading and trailing whitespace from source list .
    2. If source list is a case insensitive match for the string ‘none’ (including the quotation marks), return the empty set.
    3. Let set of source expressions be the empty set.
    4. For each token returned by splitting source list on spaces, if the token matches the grammar for source-expression , add the token to the set of source expressions .
    5. Return the set of source expressions .

    Note: Characters like U+003B SEMICOLON ( ; ) and U+002C COMMA ( , ) cannot appear in source expressions directly: if you’d like to include these characters in a source expression, they must be percent encoded as %3B and %2C respectively.

    4.2.2 Matching Source Expressions

    A URI is said to if the following algorithm returns does match:

    1. Normalize the URI according to Section 6 of RFC3986.
    2. If the source expression a consists of a single U+002A ASTERISK character ( * ), and the URI’s scheme is not of a type designating a globally unique identifier, (such as blob: , data: , or filesystem: ) then return does match.
    3. If the source expression matches the grammar for scheme-source :
      1. If the URI’s scheme is a case-insensitive match for the source expression’s scheme-part , return does match.
      2. Otherwise, return does not match.
    4. If the source expression matches the grammar for host-source :
      1. If the URI does not contain a host, then return does not match.
      2. Let uri-scheme , uri-host , and uri-port be the scheme, host, and port of the URI, respectively. If the URI does not have a port, then let uri-port be the default port for uri-scheme . Let uri-path be the path of the URI after decoding percent-encoded characters. If the URI does not have a path, then let uri-path be the U+002F SOLIDUS character ( / ).
      3. If the source expression has a scheme-part that is not a case insensitive match for uri-scheme , then return does not match.
      4. If the source expression does not have a scheme, return does not match if
        1. the scheme of the protected resource’s URI is a case insensitive match for HTTP , and uri-scheme is not a case insensitive match for either HTTP or HTTPS
        2. the scheme of the protected resource’s URI is not a case insensitive match for HTTP , and uri-scheme is not a case insensitive match for the scheme of the protected resource’s URI.
      5. If the first character of the source expression’s host-part is an U+002A ASTERISK character ( * ) and the remaining characters, including the leading U+002E FULL STOP character ( . ), are not a case insensitive match for the rightmost characters of uri-host , then return does not match.
      6. If the first character of the source expression’s host-part is not an U+002A ASTERISK character ( * ) and uri-host is not a case insensitive match for the source expression’s host-part , then return does not match.
      7. If the source expression does not contain a port-part and uri-port is not the default port for uri-scheme , then return does not match.
      8. If the source expression does contain a port-part , then return does not match if
        1. port-part does not contain an U+002A ASTERISK character ( * ), and
        2. port-part does not represent the same number as uri-port .
      9. If the source expression contains a non-empty path-part , and the URI is not the result of a redirect, then:
        1. Let decoded-path be the result of decoding path-part ’s percent-encoded characters.
        2. If the final character of decoded-path is the U+002F SOLIDUS character ( / ), and decoded-path is not a prefix of uri-path , then return does not match.
        3. If the final character of decoded-path is not the U+002F SOLIDUS character ( / ), and decoded-path is not an exact match for uri-path then return does not match.
      10. Otherwise, return does match.
    5. If the source expression is a case insensitive match for ‘self’ (including the quotation marks), then:
      1. Return does match if the URI has the same scheme, host, and port as the protected resource’s URI (using the default port for the appropriate scheme if either or both URIs are missing ports).
    6. Otherwise, return does not match.

    A URI is said to if the following conditions are met:

    1. The URI matches at least one source expression in the set of source expressions obtained by parsing the source list.
    2. At least one of the following is true:
      1. The URI is one of not the result of a redirect.
      2. The set of source expressions obtained by parsing the source list contains the source expression ‘unsafe-redirect’ .
      3. The source list is the U+002A ASTERISK character ( * ).

    Note: No URIs match an empty set of source expressions, such as the set obtained by parsing the source list ‘none’ .

    4.2.2.1 Security Considerations for GUID URI schemes

    This section is not normative.

    As defined above, special URI schemes that refer to specific pieces of unique content, such as «data:», «blob:» and «filesystem:» are excluded from matching a policy of * and must be explicitly listed. Policy authors should note that the content of such URIs is often derived from a response body or execution in a Document context, which may be unsafe. Especially for the default-src and script-src directives, policy authors should be aware that allowing «data:» URIs is equivalent to unsafe-inline and allowing «blob:» or «filesystem:» URIs is equivalent to unsafe-eval .

    4.2.2.2 Path Matching

    This section is not normative.

    The rules for matching source expressions that contain paths are simpler than they look: paths that end with the ‘/’ character match all files in a directory and its subdirectories. Paths that do not end with the ‘/’ character match only one specific file. A few examples should make this clear:

    1. The source expression example.com has no path, and therefore matches any file served from that host.
    2. The source expression example.com/scripts/ matches any file in the scripts directory of example.com , and any of its subdirectories. For example, both https://example.com/scripts/file.js and https://example.com/scripts/js/file.js would match.
    3. The source expression example.com/scripts/file.js matches only the file named file.js in the scripts directory of example.com .
    4. Likewise, the source expression example.com/js matches only the file named js . In particular, note that it would not match files inside a directory named js . Files like example.com/js/file.js would be matched only if the source expression ended with a trailing «/», as in example.com/js/ .

    Note: Query strings have no impact on matching: the source expression example.com/file?key=value matches all of https://example.com/file , https://example.com/file?key=value , https://example.com/file?key=notvalue , and https://example.com/file?notkey=notvalue .

    4.2.2.3 Paths and Redirects

    To avoid leaking path information cross-origin (as discussed in Egor Homakov’s Using Content-Security-Policy for Evil), the matching algorithm ignores the path component of a source expression if the resource being loaded is the result of a redirect. For example, given a page with an active policy of img-src example.com not-example.com/path :

    • Directly loading https://not-example.com/not-path would fail, as it doesn’t match the policy.
    • Directly loading https://example.com/redirector would pass, as it matches example.com .
    • Assuming that https://example.com/redirector delivered a redirect response pointing to https://not-example.com/not-path , the load would succeed, as the initial URL matches example.com , and the redirect target matches not-example.com/path if we ignore its path component.

    This restriction reduces the granularity of a document’s policy when redirects are in play, which isn’t wonderful, but given that we certainly don’t want to allow brute-forcing paths after redirects, it seems a reasonable compromise.

    The relatively long thread «Remove paths from CSP?» from public-webappsec@w3.org has more detailed discussion around alternate proposals.

    4.2.3 The nonce attribute

    Nonce sources require a new attribute to be added to both script and style elements: .

    This attribute reflects the value of the element’s nonce content attribute. This attribute reflects the value of the element’s nonce content attribute.

    4.2.4 Valid Nonces

    An element has a for a set of source expressions if the value of the element’s nonce attribute after stripping leading and trailing whitespace is a case-sensitive match for the nonce-value component of at least one nonce-source expression in set of source expressions .

    4.2.5 Valid Hashes

    An is the script block’s source for script elements, or the value of the element’s textContent IDL attribute for non- script elements such as style .

    The for is the result of applying an algorithm to the element’s content.

    To determine whether element has a for a set of source expressions , execute the following steps:

    1. Let hashes be a list of all hash-source expressions in set of source expressions .
    2. For each hash in hashes :
      1. Let algorithm be:
        • SHA-256 if the hash-algo component of hash is a case-insensitive match for the string «sha256»
        • SHA-384 if the hash-algo component of hash is a case-insensitive match for the string «sha384»
        • SHA-512 if the hash-algo component of hash is a case-insensitive match for the string «sha512»
      2. Let expected be the hash-value component of hash .
      3. Let actual be the base64 encoding of the binary digest of element ’s content using the algorithm algorithm.
      4. If actual is a case-sensitive match for expected , return true and abort these steps.
    3. Return false.

    Note: If an element has an invalid hash, it would be helpful if the user agent reported the failure to the author by adding a warning message containing the actual hash value.

    4.3 Media Type List

    The plugin-types directive uses a value consisting of a .

    Each in the media type list represents a specific type of resource that can be retrieved and used to instantiate a plugin in the protected resource.

    4.3.1 Parsing

    To media type list , the user agent MUST use an algorithm equivalent to the following:

    1. Let the set of media types be the empty set.
    2. For each token returned by splitting media type list on spaces, if the token matches the grammar for media-type , add the token to the set of media types . Otherwise ignore the token.
    3. Return the set of media types .

    4.3.2 Matching

    A media type if, and only if, the media type is a case-insensitive match for at least one token in the set of media types obtained by parsing the media type list.

    4.4 Reporting

    To , the user agent MUST use an algorithm equivalent to the following:

    1. If the origin of uri is a globally unique identifier (for example, uri has a scheme of data , blob , or filesystem ), then abort these steps, and return the ASCII serialization of uri ’s scheme.
    2. If the origin of uri is not the same as the origin of the protected resource, then abort these steps, and return the ASCII serialization of uri ’s origin.
    3. Return uri , with any fragment component removed.

    To , the user agent MUST use an algorithm equivalent to the following:

    1. Prepare a JSON object violation with the following keys and values: blocked-uri The originally requested URI of the resource that was prevented from loading, stripped for reporting, or the empty string if the resource has no URI (inline script and inline style, for example). document-uri The address of the protected resource, stripped for reporting. effective-directive The name of the policy directive that was violated. This will contain the directive whose enforcement triggered the violation (e.g. » script-src «) even if that directive does not explicitly appear in the policy, but is implicitly activated via the default-src directive. original-policy The original policy, as received by the user agent. referrer The referrer attribute of the protected resource, or the empty string if the protected resource has no referrer. status-code The status-code of the HTTP response that contained the protected resource, if the protected resource was obtained over HTTP. Otherwise, the number 0. violated-directive The policy directive that was violated, as it appears in the policy. This will contain the default-src directive in the case of violations caused by falling back to the default sources when enforcing a directive.
    2. If a specific line or a specific file can be identified as the cause of the violation (for example, script execution that violates the script-src directive), the user agent MAY add the following keys and values to violation : The URI of the resource where the violation occurred, stripped for reporting. line-number The line number in source-file on which the violation occurred. column-number The column number in source-file on which the violation occurred.
    3. Return violation .

    Note: blocked-uri will not contain the final location of a resource that was blocked after one or more redirects. It instead will contain only the location that the protected resource requested, before any redirects were followed.

    To , the user agent MUST use an algorithm equivalent to the following:

    1. Prepare a JSON object report object with a single key, csp-report , whose value is the result of generating a violation report object.
    2. Let report body be the JSON stringification of report object .
    3. For each report URI in the set of report URIs:
      1. If the user agent has already sent a violation report for the protected resource to report URI , and that report contained an entity body that exactly matches report body , the user agent MAY abort these steps and continue to the next report URI .
      2. Queue a task to fetch report URI from the origin of the protected resource, with the synchronous flag not set, using HTTP method POST , with a Content-Type header field of application/csp-report , and an entity body consisting of report body . If the origin of report URI is not the same as the origin of the protected resource, the block cookies flag MUST also be set. The user agent MUST NOT follow redirects when fetching this resource. (Note: The user agent ignores the fetched resource.) The task source for these tasks is the .

    To , the user agent MUST:

    Note: This section of the specification should not be interpreted as limiting user agents’ ability to apply restrictions to violation reports in order to limit data leakage above and beyond what these algorithms specify.

    5 Processing Model

    To a policy, the user agent MUST parse the policy and enforce each of the directives contained in the policy, where the specific requirements for enforcing each directive are defined separately for each directive (See §7 Directives, below).

    Generally speaking, enforcing a directive prevents the protected resource from performing certain actions, such as loading scripts from URIs other than those indicated in a source list. These restrictions make it more difficult for an attacker to abuse an injection vulnerability in the resource because the attacker will be unable to usurp the resource’s privileges that have been restricted in this way.

    Note: User agents may allow users to modify or bypass policy enforcement through user preferences, bookmarklets, third-party additions to the user agent, and other such mechanisms.

    To a policy, the user agent MUST parse the policy and monitor each of the directives contained in the policy.

    Monitoring a directive does not prevent the protected resource from undertaking any actions. Instead, any actions that would have been prevented by the directives are allowed, but a violation report is generated and reported to the developer of the web application. Monitoring a policy is useful for testing whether enforcing the policy will cause the web application to malfunction.

    A server MAY cause user agents to monitor one policy while enforcing another policy by returning both Content-Security-Policy and Content-Security-Policy-Report-Only header fields. For example, if a server operator may wish to enforce one policy but experiment with a stricter policy, she can monitor the stricter policy while enforcing the original policy. Once the server operator is satisfied that the stricter policy does not break the web application, the server operator can start enforcing the stricter policy.

    If the user agent monitors or enforces a policy that does not contain any directives, the user agent SHOULD report a warning message in the developer console.

    If the user agent monitors or enforces a policy that contains an unrecognized directive, the user agent SHOULD report a warning message in the developer console indicating the name of the unrecognized directive.

    If the user agent monitors or enforces a policy that contains a directive that contains a source list, then the user agent MUST set a CSP Request Header when requesting cross-origin resources, as described in §3.4 The CSP HTTP Request Header.


    5.1 Workers

    Whenever a user agent runs a worker:

    • If the worker’s script’s origin is a globally unique identifier (for example, the worker’s script’s URL has a scheme of data , blob , or filesystem ), then:
      • If the user agent is enforcing a CSP policy for the owner document , the user agent MUST enforce the CSP policy for the worker.
      • If the user agent is monitoring a CSP policy for the owner document , the user agent MUST monitor the CSP policy for the worker.
    • Otherwise:
      • If the worker’s script is delivered with a Content-Security-Policy HTTP header containing the value policy , the user agent MUST enforce policy for the worker.
      • If the worker’s script is delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy , the user agent MUST monitor policy for the worker.

    5.2 srcdoc IFrames

    Whenever a user agent creates an iframe srcdoc document in a browsing context nested in the protected resource, if the user agent is enforcing any policies for the protected resource, the user agent MUST enforce those policies on the iframe srcdoc document as well.

    Whenever a user agent creates an iframe srcdoc document in a browsing context nested in the protected resource, if the user agent is monitoring any policies for the protected resource, the user agent MUST monitor those policies on the iframe srcdoc document as well.

    6 Script Interfaces

    6.1 SecurityPolicyViolationEvent Interface

    6.2 SecurityPolicyViolationEventInit Interface

    6.3 Firing Violation Events

    To , the user agent MUST use an algorithm equivalent to the following:

    1. Let report object be the result of generating a violation report object.
    2. Queue a task to fire an event named securitypolicyviolation using the SecurityPolicyViolationEvent interface with the following initializations:
      • blockedURI MUST be initialized to the value of report object ’s blocked-uri key.
      • documentURI MUST be initialized to the value of report object ’s document-uri key.
      • effectiveDirective MUST be initialized to the value of report object ’s effective-directive key.
      • originalPolicy MUST be initialized to the value of report object ’s original-policy key.
      • referrer MUST be initialized to the value of report object ’s referrer key.
      • violatedDirective MUST be initialized to the value of report object ’s violated-directive key.
      • sourceFile MUST be initialized to the value of report object ’s source-file key.
      • lineNumber MUST be initialized to the value of report object ’s line-number key.
      • columnNumber MUST be initialized to the value of report object ’s column-number key.

    7 Directives

    This section describes the content security policy directives introduced in this specification. Directive names are case insensitive.

    In order to protect against Cross-Site Scripting (XSS), web application authors SHOULD include:

    • both the script-src and object-src directives, or
    • include a default-src directive, which covers both scripts and plugins.

    In either case, authors SHOULD NOT include either ‘unsafe-inline’ or data: as valid sources in their policies. Both enable XSS attacks by allowing code to be included directly in the document itself; they are best avoided completely.

    Redirects are another area of potential concern. Authors SHOULD NOT include ‘unsafe-redirect’ as valid sources in their policies. It makes it more difficult to reason about the complete set of resources that a policy allows, especially given the path behavior outlined in the §4.2.2.3 Paths and Redirects section.

    7.1 base-uri

    The directive restricts the URIs that can be used to specify the document base URL. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Step 4 of the algorithm defined in HTML5 to obtain a document’s base URL MUST be changed to:

    1. If the previous step was not successful, or the result of the previous step does not match the allowed base URIs, then the document base URL is fallback base URL . Otherwise, it is the result of the previous step.

    7.2 child-src

    The directive governs the creation of nested browsing contexts as well as Worker execution contexts. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the child-src directive’s value as a source list if a child-src directive is explicitly specified, and otherwise to the default sources.

    7.2.1 Nested Browsing Contexts

    To enforce the child-src directive the user agent MUST enforce the frame-src directive.

    7.2.2 Workers

    Whenever the user agent fetches a URL while processing the Worker or SharedWorker constructors [WORKERS], the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation if the URI does not match the allowed child sources.

    7.3 connect-src

    The directive restricts which URIs the protected resource can load using script interfaces. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the connect-src directive’s value as a source list if the policy contains an explicit connect-src directive, or otherwise to the default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed connection targets, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Processing the send() method of an XMLHttpRequest object.
    • Processing the WebSocket constructor.
    • Processing the EventSource constructor.
    • Sending a beacon via the sendBeacon() method [BEACON]

    7.3.1 Usage

    This section is not normative.

    JavaScript offers a few mechanisms that directly connect to an external server to send or receive information. EventSource maintains an open HTTP connection to a server in order to receive push notifications, WebSockets open a bidirectional communication channel between your browser and a server, and XMLHttpRequest makes arbitrary HTTP requests on your behalf. These are powerful APIs that enable useful functionality, but also provide tempting avenues for data exfiltration.

    The connect-src directive allows you to ensure that these sorts of connections are only opened to origins you trust. Sending a policy that defines a list of source expressions for this directive is straightforward. For example, to limit connections to only example.com , send the following header:

    All of the following will fail with the preceding directive in place:

    • new WebSocket(«wss://evil.com/»);
    • (new XMLHttpRequest()).open(«GET», «https://evil.com/», true);
    • new EventSource(«https://evil.com»);

    7.4 default-src

    The directive sets a default source list for a number of directives. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Let the be the result of parsing the default-src directive’s value as a source list if a default-src directive is explicitly specified, and otherwise the U+002A ASTERISK character (*).

    To enforce the default-src directive, the user agent MUST enforce the following directives:

    If not specified explicitly in the policy, the directives listed above will use the default sources as their source list.

    7.4.1 Usage

    This section is not normative.

    default-src , as the name implies, serves as a default source list which the other source list-style directives will use as a fallback if they’re not otherwise explicitly set. That is, consider the following policy declaration:

    Under this policy, fonts, frames, images, media, objects, scripts, and styles will all only load from the same origin as the protected resource, and connections will only be made to the same origin. Adding a more specific declaration to the policy would completely override the default source list for that resource type.

    Under this new policy, fonts, frames, and etc. continue to be load from the same origin, but scripts will only load from example.com . There’s no inheritance; the script-src directive sets the allowed sources of script, and the default list is not used for that resource type.

    Given this behavior, one good way of building a policy for a site would be to begin with a default-src of ‘none’ , and to build up a policy from there that contains only those resource types which are actually in use for the page you’d like to protect. If you don’t use webfonts, for instance, there’s no reason to specify a source list for font-src ; specifying only those resource types a page uses ensures that the possible attack surface for that page remains as small as possible.

    7.5 font-src

    The directive restricts from where the protected resource can load fonts. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the font-src directive’s value as a source list if the policy contains an explicit font-src , or otherwise to the default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed font sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for display in a font, such as when processing the Cascading Style Sheets (CSS) rule.

    7.6 form-action

    The restricts which URIs can be used as the action of HTML form elements. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed form actions, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Processing an HTML form element.
    • Pinging an endpoint during hyperlink auditing

    Note: form-action does not fall back to the default sources when the directive is not defined. That is, a policy that defines default-src ‘none’ but not form-action will still allow form submissions to any target.

    7.7 frame-ancestors

    The directive indicates whether the user agent should allow embedding the resource using a frame , iframe , object , embed or applet tag, or equivalent functionality in non-HTML resources. Resources can use this directive to avoid many UI Redressing [UIREDRESS] attacks by avoiding being embedded into potentially hostile contexts.

    The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the frame-ancestors directive’s value as a source list. If a frame-ancestors directive is not explicitly included in the policy, then allowed frame ancestors is » * «.

    To enforce the frame-ancestors directive, whenever the user agent would load the protected resource into a nested browsing context, the user agent MUST perform the following steps:

    1. Let nestedContext be the nested browsing context into which the protected resource is being loaded.
    2. Let ancestorList be the list of all ancestors of nestedContext .
    3. For each ancestorContext in ancestorList :
      1. Let document be ancestorContext ’s active document.
      2. If document ’s URL does not match the allowed frame ancestors, the user agent MUST:
        1. Abort loading the protected resource.
        2. Act as if it received an empty HTTP 200 response.
        3. Parse a sandboxing directive using the empty string as the input and the newly created document’s forced sandboxing flag set as the output.

    Steps 2.2 and 2.3 ensure that the blocked frame appears to be a normal cross-origin document’s load. If these steps are ignored, leakage of a document’s policy state is possible. The user agent MAY implement these steps by instead redirecting the user to friendly error page in a unique origin which provides the option of opening the blocked page in a new top-level browsing context.

    The frame-ancestors directive MUST be ignored when monitoring a policy, and when a contained in a policy defined via a meta element.

    Note: frame-ancestors does not fall back to the default sources when the directive is not defined. That is, a policy that defines default-src ‘none’ but not frame-ancestors will still allow the resource to be framed from anywhere.

    When generating a violation report for a frame-ancestors violation, the user agent MUST NOT include the value of the embedding ancestor as a blocked-uri value unless it is same-origin with the protected resource, as disclosing the value of cross-origin ancestors is a violation of the Same-Origin Policy.

    7.7.1 Relation to X-Frame-Options

    This directive is similar to the X-Frame-Options header that several user agents have implemented. The ‘none’ source expression is roughly equivalent to that header’s DENY , ‘self’ to SAMEORIGIN , and so on. The major difference is that many user agents implement SAMEORIGIN such that it only matches against the top-level document’s location. This directive checks each ancestor. If any ancestor doesn’t match, the load is cancelled. [RFC7034]

    The frame-ancestors directive obsoletes the X-Frame-Options header. If a resource has both policies, the frame-ancestors policy SHOULD be enforced and the X-Frame-Options policy SHOULD be ignored.

    7.7.2 Multiple Host Source Values

    This section is not normative.

    Multiple source-list expressions are allowed in a single policy (in contrast to X-Frame-Options , which allows only one) to enable scenarios involving embedded application components that are multiple levels below the top-level browsing context.

    Many common scenarios for permissioned embedding (e.g. embeddable payment, sharing or social apps) involve potentially many hundreds or thousands of valid source-list expressions, but it is strongly recommended against accommodating such scenarios with a static frame-ancestors directive listing multiple values. In such cases it is beneficial to generate this value dynamically, based on an HTTP Referer header or an explicitly passed-in value, to allow only the sources necessary for each given embedding of the resource.

    Consider a service providing a payments application at https://payments/makeEmbedded . The service allows this resource to be embedded by both merchant Alice and merchant Bob, who compete with each other. Sending:

    would allow Bob to re-frame Alice’s resource and create fraudulent clicks, perhaps discrediting Alice with her customers or the payments service. If the payments service used additional information (e.g. as part of a URL like https://payments/makeEmbedded?merchant=alice ) to send individually-tailored headers listing only the source-list expressions needed by each merchant, this attack would be eliminated.

    7.8 frame-src

    The directive is deprecated. Authors who wish to govern nested browsing contexts SHOULD use the child-src directive instead.

    The frame-src directive restricts from where the protected resource can embed frames. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the frame-src directive’s value as a source list if the policy contains an explicit frame-src , or otherwise to the list of allowed child sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed frame sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for display in a nested browsing context in the protected resource created by an iframe or a frame element.
    • Navigated such a nested browsing context.

    7.9 img-src

    The directive restricts from where the protected resource can load images. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the img-src directive’s value as a source list if the policy contains an explicit img-src , or otherwise to the list of default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed image sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for an image, such as when processing the src or srcset attributes of an img element, the src attribute of an input element with a type of image , the poster attribute of a video element, the url() , or values on any Cascading Style Sheets (CSS) property that is capable of loading an image [CSS4-IMAGES], or the href attribute of a link element with an image-related rel attribute, such as icon .

    7.10 media-src

    The directive restricts from where the protected resource can load video, audio, and associated text tracks. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the media-src directive’s value as a source list if the policy contains an explicit media-src , or otherwise to the list of default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed media sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for a video or audio clip, such as when processing the src attribute of a video , audio , source , or track elements.

    7.11 object-src

    The directive restricts from where the protected resource can load plugins. The syntax for the name and value of the directive are described by the following ABNF grammar:


    The term refers to the result of parsing the object-src directive’s value as a source list if the policy contains an explicit object-src , or otherwise to the list of default sources.

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed object sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting data for a plugin, such as when processing the data attribute of an object element, the src attribute of an embed elements, or the code or archive attributes of an applet element.
    • Requesting data for display in a nested browsing context in the protected resource created by an object or an embed element.
    • Navigating such a nested browsing context.

    It is not required that the consumer of the element’s data be a plugin in order for the object-src directive to be enforced. Data for any object , embed , or applet element MUST match the allowed object sources in order to be fetched. This is true even when the element data is semantically equivalent to content which would otherwise be restricted by one of the other directives, such as an object element with a text/html MIME type.

    Whenever the user agent would load a plugin without an associated URI (e.g., because the object element lacked a data attribute), if the protected resource’s URI does not match the allowed object sources, the user agent MUST NOT load the plugin.

    7.12 plugin-types

    The directive restricts the set of plugins that can be invoked by the protected resource by limiting the types of resources that can be embedded. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Whenever the user agent would instantiate a plugin to handle resource while enforcing the plugin-types directive, the user agent MUST instead act as though the plugin reported an error and report a violation if any of the following conditions hold:

    • The plugin is embedded into the protected resource via an object or embed element that does not explicitly declare a MIME type via a type attribute.
    • resource ’s media type does not match the list of allowed plugin media types.
    • The plugin is embedded into the protected resource via an object or embed element, and the media type declared in the element’s type attribute is not a case-insensitive match for the resource ’s media type.
    • The plugin is embedded into the protected resource via an applet element, and resource ’s media type is not a case-insensitive match for application/x-java-applet .

    Note: In any of these cases, acting as though the plugin reported an error will cause the user agent to display the fallback content.

    Whenever the user agent creates a plugin document in a nested browsing context in the protected resource, if the user agent is enforcing any plugin-types directives for the protected resource, the user agent MUST enforce those plugin-types directives on the plugin document as well.

    Whenever the user agent creates a plugin document in a nested browsing context in the protected resource, if the user agent is monitoring any plugin-types directives for the protected resource, the user agent MUST monitor those plugin-types directives on the plugin document as well.

    7.12.1 Usage

    This section is not normative.

    The plugin-types directive whitelists a certain set of MIME types that can be embedded in a protected resource. For example, a site might want to ensure that PDF content loads, but that no other plugins can be instantiated. The following directive would satisfy that requirement:

    Resources embedded via an embed or object element delivered with an application/pdf content type would be rendered in the appropriate plugin; resources delivered with some other content type would be blocked. Multiple types can be specified, in any order. If the site decided to additionally allow Flash at some point in the future, it could do so with the following directive:

    Note: Wildcards are not accepted in the plugin-types directive. Only the resource types explicitly listed in the directive will be allowed.

    7.12.2 Predeclaration of expected media types

    This section is not normative.

    Enforcing the plugin-types directive requires that object and embed elements declare the expected media type of the resource they include via the type attribute. If an author expects to load a PDF, she could specify this as follows:

    If resource isn’t actually a PDF file, it won’t load. This prevents certain types of attacks that rely on serving content that unexpectedly invokes a plugin other than that which the author intended.

    Note: resource will not load in this scenario even if its media type is otherwise whitelisted: resources will only load when their media type is whitelisted and matches the declared type in their containing element.

    7.13 referrer

    The directive specifies the referrer policy [REFERRER] that the user agent applies when determining what referrer information should be included with requests made, and with browsing contexts created from the context of the protected resource. The syntax for the name and value of the directive are described by the following ABNF grammar:

    Note: The directive name does not share the HTTP header’s misspelling.

    When enforcing the referrer directive, the user agent MUST execute [REFERRER]’s Set environment ’s referrer policy to policy . algorithm on the protected resource’s JavaScript global environment using the result of executing the Determine token ’s Policy algorithm on the referrer directive’s value.

    7.13.1 Usage

    This section is not normative.

    A protected resource can prevent referrer leakage by specifying no-referrer as the value of its policy’s referrer directive:

    This will cause all requests made from the protected resource’s context to have an empty Referer [sic] header.

    7.14 reflected-xss

    The directive instructs a user agent to activate or deactivate any heuristics used to filter or block reflected cross-site scripting attacks. The syntax for the name and value of the directive are described by the following ABNF grammar:

    A user agent with support for XSS protection MUST enforce this directive as follows:

    • If the value of the directive is allow , the user agent MUST disable its active protections against reflected cross-site scripting attacks for the protected resource.
    • If the value of the directive is filter , the user agent MUST enable its active protections against reflected cross-site scripting attacks for the protected resource. This might result in filtering script that is believed to be reflected being filtered or selectively blocking script execution.
    • If the value of the directive is block , the user agent MUST stop rendering the protected resource upon detection of reflected script, and instead act as if there was a fatal network error and no resource was obtained, andreport a violation:

    If the user agent’s active protections against reflected cross-site scripting attacks detect or prevent script execution, the user agent MUST report a violation.

    Note: The reflected-xss directive will be ignored if contained within a meta element.

    7.14.1 Relationship to X-XSS-Protection

    This directive is meant to subsume the functionality provided by the proprietary X-XSS-Protection HTTP header which is supported by a number of user agents. Roughly speaking:

    • reflected-xss allow is equivalent to X-XSS-Protection: 0
    • reflected-xss filter is equivalent to X-XSS-Protection: 1
    • reflected-xss block is equivalent to X-XSS-Protection: 1; mode=block

    7.15 report-uri

    The directive specifies a URI to which the user agent sends reports about policy violation. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The is the value of the report-uri directive, each resolved relative to the protected resource’s URI.

    The process of sending violation reports to the URIs specified in this directive’s value is defined in this document’s §4.4 Reporting section.

    Note: The report-uri directive will be ignored if contained within a meta element.

    7.16 sandbox

    The directive specifies an HTML sandbox policy that the user agent applies to the protected resource. The syntax for the name and value of the directive are described by the following ABNF grammar:

    When enforcing the sandbox directive, the user agent MUST parse a sandboxing directive using the directive-value as the input and protected resource’s forced sandboxing flag set as the output. [HTML5]

    Note: The sandbox directive will be ignored when monitoring a policy, and when contained in a policy defined via a meta element.

    7.16.1 Usage

    This section is not normative.

    HTML5 defines a sandbox attribute for iframe elements, intended to allow web authors to reduce the risk of including potentially untrusted content by imposing restrictions on that content’s abilities. When the attribute is set, the content is forced into a unique origin, prevented from submitting forms, running script, creating or navigating other browsing contexts, and prevented from running plugins. These restrictions can be loosened by setting certain flags as the attribute’s value.

    The sandbox directive allows any resource, framed or not, to ask for the same sorts of restrictions to be applied to itself.

    For example, a message board or email system might provide downloads of arbitrary attachments provided by other users. Attacks that rely on tricking a client into rendering one of these attachments could be mitigated by requesting that resources only be rendered in a very restrictive sandbox. Sending the sandbox directive with an empty value establishes such an environment:

    More trusted resources might be allowed to run in an environment with fewer restrictions by adding allow-* flags to the directive’s value. For example, you can allow a page that you trust to run script, while ensuring that it isn’t treated as same-origin with the rest of your site. This can be accomplished by sending the sandbox directive with the allow-scripts flag:

    The set of flags available to the CSP directive should match those available to the iframe attribute. Currently, those include:

    Note: Like the rest of Content Security Policy, the sandbox directive is meant as a defense-in-depth. Web authors would be well-served to use it in addition to standard sniffing-mitigation and privilege-reduction techniques.

    7.17 script-src

    The directive restricts which scripts the protected resource can execute. The directive also controls other resources, such as XSLT style sheets [XSLT], which can cause the user agent to execute script. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the script-src directive’s value as a source list if the policy contains an explicit script-src , or otherwise to the default sources.

    If ‘unsafe-inline’ is not in the list of allowed script sources, or if at least one nonce-source or hash-source is present in the list of allowed script sources:

    • Whenever the user agent would execute an inline script from a script element that lacks a valid nonceand lacks a valid hash for the allowed script sources, instead the user agent MUST NOT execute script, and MUST report a violation.
    • Whenever the user agent would execute an inline script from an inline event handler, instead the user agent MUST NOT execute script, and MUST report a violation.
    • Whenever the user agent would execute script contained in a javascript URI, instead the user agent MUST NOT execute the script, and MUST report a violation.

    If ‘unsafe-eval’ is not in allowed script sources:

    • Instead of evaluating their arguments, both operator eval and function eval [ECMA-262] MUST throw an EvalError exception.
    • When called as a constructor, the function Function [ECMA-262] MUST throw an EvalError exception.
    • When called with a first argument that is not callable (a string, for example), the setTimeout() function MUST return zero without creating a timer.
    • When called with a first argument that is not callable (a string, for example), the setInterval() function MUST return zero without creating a timer.

    Whenever the user agent fetches a URI (including when following redirects) in the course of one of the following activities, if the URI does not match the allowed script sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting a script while processing the src attribute of a script element that lacks a valid nonce for the allowed script sources.
    • Requesting a script while invoking the importScripts method on a WorkerGlobalScope object. [WORKERS]
    • Requesting an HTML component, such as when processing the href attribute of a link element with a rel attribute containing the token import . [HTML-IMPORTS]
    • Requesting an Extensible Stylesheet Language Transformations (XSLT) [XSLT], such as when processing the processing directive in an XML document [XML11], the href attributes on and elements.

    7.17.1 Nonce usage for script elements

    This section is not normative.

    The script-src directive lets developers specify exactly which script elements on a page were intentionally included for execution. Ideally, developers would avoid inline script entirely and whitelist scripts by URL. However, in some cases, removing inline scripts can be difficult or impossible. For those cases, developers can whitelist scripts using a randomly generated nonce.

    Usage is straightforward. For each request, the server generates a unique value at random, and includes it in the Content-Security-Policy header:

    This same value is then applied as a nonce attribute to each script element that ought to be executed. For example, if the server generated the random value Nc3n83cnSAd3wc3Sasdfn939hc3 , the server would send the following policy:

    Script elements can then execute either because their src URLs are whitelisted or because they have a valid nonce:

    Note that the nonce’s value is not a hash or signature that verifies the contents of the script resources. It’s quite simply a random string that informs the user agent which scripts were intentionally included in the page.

    Script elements with the proper nonce execute, regardless of whether they’re inline or external. Script elements without the proper nonce don’t execute unless their URLs are whitelisted. Even if an attacker is able to inject markup into the protected resource, the attack will be blocked by the attacker’s inability to guess the random value.

    7.17.2 Hash usage for script elements

    This section is not normative.

    The script-src directive lets developers whitelist a particular inline script by specifying its hash as an allowed source of script.

    Usage is straightforward. The server computes the hash of a particular script block’s contents, and includes the base64 encoding of that value in the Content-Security-Policy header:

    Each inline script block’s contents are hashed, and compared against the whitelisted value. If there’s a match, the script is executed. For example, the SHA-256 digest of alert(‘Hello, world.’); is YWIzOWNiNzJjNDRlYzc4MTgwMDhmZDlkOWI0NTAyMjgyY2MyMWJlMWUyNjc1ODJlYWJhNjU5MGU4NmZmNGU3OAo= . If the server sent the following header:

    Then the following script tag would result in script execution:

    Whitespace is significant. The following scripts blocks would not hash to the same value, and would therefore not execute:

    Note also that the hash applies only to inline script. An externalized script containing the value alert(‘Hello, world.’); would not execute if its origin was not whitelisted as a valid source of script.

    7.18 style-src

    The directive restricts which styles the user may applies to the protected resource. The syntax for the name and value of the directive are described by the following ABNF grammar:

    The term refers to the result of parsing the style-src directive’s value as a source list if the policy contains an explicit style-src , or otherwise to the default sources.

    If ‘unsafe-inline’ is not in the list of allowed style sources, or if at least one nonce-source or hash-source is present in the list of allowed style sources:

    • Whenever the user agent would apply style from a style element that lacks a valid nonceand lacks a valid hash for the allowed style sources, instead the user agent MUST ignore the style, and MUST report a violation.
    • Whenever the user agent would apply style from a style attribute, instead the user agent MUST ignore the style, and MUST report a violation.

    Note: These restrictions on inline do not prevent the user agent from applying style from an external stylesheet (e.g., found via
    ).

    If ‘unsafe-eval’ is not in allowed style sources, then:

    • Whenever the user agent would invoke the Cascading Style Sheets Object Model algorithms insert a CSS rule, parse a CSS rule, parse a CSS declaration block, or parse a group of selectors instead the user agent MUST throw a SecurityError exception and terminate the algorithm. This would include, for example, all invocations of CSSOM’s various cssText setters and insertRule methods. [CSSOM][HTML5]

    Whenever the user agent fetches a URI in the course of one of the following activities, if the URI does not match the allowed style sources, the user agent MUST act as if there was a fatal network error and no resource was obtained, and report a violation:

    • Requesting external style sheets, such as when processing the href attribute of a link element with a rel attribute containing the token stylesheet or when processing the directive in a stylesheet.

    Note: The style-src directive does not restrict the use of XSLT. XSLT is restricted by the script-src directive because the security consequences of including an untrusted XSLT stylesheet are similar to those incurred by including an untrusted script.

    7.18.1 Nonce usage for style elements

    This section is not normative.

    See the script-src nonce usage information for detail; the application of nonces to style elements is similar enough to avoid repetition here.

    7.18.2 Hash usage for style elements

    This section is not normative.

    See the script-src hash usage information for detail; the application of hashes to style elements is similar enough to avoid repetition here.

    8 Examples

    8.1 Sample Policy Definitions

    This section provides some sample use cases and supporting policies.

    This policy allows inline content (such as inline script elements), use of eval , and loading resources over https . Note: This policy does not provide any protection from cross-site scripting vulnerabilities.

    The inline script elements would then only execute if they contained a matching nonce attribute:

    8.2 Sample Violation Report

    This section contains an example violation report the user agent might sent to a server when the protected resource violations a sample policy.

    In the following example, the user agent rendered a representation of the resource http://example.org/page.html with the following policy:

    The protected resource loaded an image from http://evil.example.com/image.png , violating the policy.


    9 Security Considerations

    9.1 Cascading Style Sheet (CSS) Parsing

    The style-src directive restricts the locations from which the protected resource can load styles. However, if the user agent uses a lax CSS parsing algorithm, an attacker might be able to trick the user agent into accepting malicious «stylesheets» hosted by an otherwise trustworthy origin.

    These attacks are similar to the CSS cross-origin data leakage attack described by Chris Evans in 2009. User agents SHOULD defend against both attacks using the same mechanism: stricter CSS parsing rules for style sheets with improper MIME types.

    9.2 Violation Reports

    The violation reporting mechanism in this document has been designed to mitigate the risk that a malicious web site could use violation reports to probe the behavior of other servers. For example, consider a malicious web site that white lists https://example.com as a source of images. If the malicious site attempts to load https://example.com/login as an image, and the example.com server redirects to an identity provider (e.g., idenityprovider.example.net ), CSP will block the request. If violation reports contained the full blocked URI, the violation report might contain sensitive information contained in the redirected URI, such as session identifiers or purported identities. For this reason, the user agent includes only the origin of the blocked URI.

    10 Implementation Considerations

    The Content-Security-Policy header is an end-to-end header. It is processed and enforced at the client and, therefore, SHOULD NOT be modified or removed by proxies or other intermediaries not in the same administrative domain as the resource.

    The originating administrative domain for a resource might wish to apply a Content-Security-Policy header outside of the immediate context of an application. For example, a large organization might have many resources and applications managed by different individuals or teams but all subject to a uniform organizational standard. In such situations, a Content-Security-Policy header might be added or combined with an existing one at a network-edge security gateway device or web application firewall. To enforce multiple policies, the administrator SHOULD combine the policy into a single header. An administrator might wish to use different combination algorithms depending on his or her intended semantics.

    One sensible policy combination algorithm is to start by allowing a default set of sources and then letting individual upstream resource owners expand the set of allowed sources by including additional origins. In this approach, the resultant policy is the union of all allowed origins in the input policies.

    Another sensible policy combination algorithm is to intersect the given policies. This approach enforces that content comes from a certain whitelist of origins, for example, preventing developers from including third-party scripts or content in violation of organizational standards and practices. In this approach, the combination algorithm forms the combined policy by removing disallowed hosts from the policies supplied by upstream resource owners.

    Interactions between the default-src and other directives SHOULD be given special consideration when combining policies. If none of the policies contains a default-src directive, adding new src directives results in a more restrictive policy. However, if one or more of the input policies contain a default-src directive, adding new src directives might result in a less restrictive policy, for example, if the more specific directive contains a more permissive set of allowed origins.

    Using a more restrictive policy than the input policy authored by the resource owner might prevent the resource from rendering or operating as intended.

    Note also that migration to HTTPS from HTTP may require updates to the policy in order to keep things running as before. Source expressions like http://example.com do not match HTTPS resources. For example, administrators SHOULD carefully examine existing policies before rolling out HTTP Strict Transport Security headers for an application. [RFC6797]

    11 IANA Considerations

    The permanent message header field registry should be updated with the following registrations: [RFC3864]

    11.1 Content-Security-Policy

    11.2 Content-Security-Policy-Report-Only

    11.3 CSP

    12 Acknowledgements

    In addition to the documents in the W3C Web Application Security working group, the work on this document is also informed by the work of the IETF websec working group, particularly that working group’s requirements document: draft-hodges-websec-framework-reqs.

    A portion of the frame-ancestors directive was originally developed as X-Frame-Options . [RFC7034]

    Conformance

    Document conventions

    Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words «MUST», «MUST NOT», «REQUIRED», «SHALL», «SHALL NOT», «SHOULD», «SHOULD NOT», «RECOMMENDED», «MAY», and «OPTIONAL» in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

    All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

    Examples in this specification are introduced with the words «for example» or are set apart from the normative text with , like this:

    This is an example of an informative example.

    Informative notes begin with the word «Note» and are set apart from the normative text with , like this:

    Note, this is an informative note.

    Conformant Algorithms

    Requirements phrased in the imperative as part of algorithms (such as «strip any leading space characters» or «return false and abort these steps») are to be interpreted with the meaning of the key word («must», «should», «may», etc) used in introducing the algorithm.

    Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

    Conformance Classes

    A must implement all the requirements listed in this specification that are applicable to user agents.

    A must implement all the requirements listed in this specification that are applicable to servers.

    RFC 3964 Security Cons >Published byMelvyn Edwards Modified over 3 years ago

    Similar presentations

    Presentation on theme: «RFC 3964 Security Cons >

    1 RFC 3964 Security Considerations for 6to4 Speaker: Chungyi Wang Adviser: Quincy Wu Date: 2007.6.25

    2 Outline Abstract Introduction 6to4 Router & Relay Router 6to4 Router 6to4 Relay Router Threat Analysis Attacks with Neighbor Discovery (ND) Messages Spoofing traffic to 6to4 nodes Reflecting traffic from 6to4 nodes Local IPv4 broadcast attack Reference

    3 Abstract The IPv6 interim mechanism 6to4 (RFC3056) uses automatic IPv6-over-IPv4 tunneling to interconnect IPv6 networks This characteristic enables a number of security threats, mainly Denial of Service It also makes it easier for nodes to spoof IPv6 addresses This document discusses these issues in more detail and suggests enhancements to alleviate the problems.

    5 Introduction (2/3) All 6to4 routers must accept and decapsulate IPv4 packets from every other 6to4 router, and from 6to4 relays. 6to4 relay routers must accept traffic from any native IPv6 node. The IPv4 and IPv6 headers may be spoofed => Denial of Service attacks

    6 Introduction (3/3) 2001:db8::1 9.0.0.2 Spoofed Address Who!?

    7 6to4 Router & Relay Router (1/2) 6to4 Router The 6to4 routers act as the border routers of a 6to4 domain 6to4 Relay Router The 6to4 relay router acts as a relay between all 6to4 domains and native IPv6 networks

    8 6to4 Router & Relay Router (2/2) 6to4 relay router 6to4 router

    9 6to4 Router (1/6) Provide IPv6 connectivity to local clients and routers. Forward packets sent to locally configured 6to4 addresses to the 6to4 network. Tunnel packets sent to foreign 6to4 addresses to the destination 6to4 router using IPv4. Tunnel packets sent to non-6to4 addresses to the configured/ closest-by-anycast 6to4 relay router. 6to4 addresses 6to4 router 6to4 relay router

    10 6to4 Router (2/6) Decapsulate directly received IPv4 packets from foreign 6to4 addresses. Decapsulate IPv4 packets received via the relay closest to the native IPv6 sources. Note that it is not easily distinguishable whether the packet was received from a 6to4 relay router or from a spoofing third party. Foreign Relay

    11 6to4 Router (3/6) Security Checks Disallow traffic: The private, broadcast, reserved IPv4 addresses From 6to4 routers in which IPv4 tunnel source does not match the 6to4 prefix The destination (IPv6) is not a global address Other 6to4 domains through 6to4 relay router or via some third party 6to4 router

    12 6to4 Router (4/6) Security Checks IPv4 0.0.0.0/8(the system has no address assigned yet) 10.0.0.0/8 (private) 127.0.0.0/8 (loopback) 172.16.0.0/12 (private) 192.168.0.0/16 (private) 169.254.0.0/16 (IANA Assigned DHCP link-local) o 224.0.0.0/4 (multicast) 240.0.0.0/4 (reserved and broadcast)

    13 6to4 Router (5/6) Security Checks IPv6 0::/16(compatible, mapped addresses, loopback, unspecified. ) fe80::/10 (link-local) fec0::/10 (site-local) ff00::/8 (any multicast)

    14 6to4 Router (6/6) Security Checks Discard traffic received: From other 6to4 domain via a 6to4 relay router For other prefixes other than one’s own 6to4 prefix.

    15 6to4 Relay Router (1/2) Decapsulates and forwards packets received from 6to4 addresses through tunneling, by using normal IPv6 routing (IPv6)  [Relay Router]  (6to4 address) Tunnels packets received through normal IPv6 routing from native addresses (IPn6)  [Relay Router]  (6to4 address)

    16 6to4 Relay Router (2/2) Security Checks Disallow traffic: The private, broadcast, reserved IPv4 addresses From 6to4 routers in which IPv4 tunnel source does not match the 6to4 prefix The destination (IPv6) is not a global address Discard traffic received: From from 6to4 routers with the destination as a 6to4 prefix (IPv6)  [Relay Router]  [6to4 Router]

    17 Threat Analysis (1/2) Types of threats Denial-of-Service (DoS) A malicious node prevents communication between the node under attack and other nodes Reflection Dos A malicious node reflects the traffic off unsuspecting nodes to a particular node (node under attack) Service theft A malicious node/site/operator may make unauthorized use of service

    18 Threat Analysis (2/2) Type of attacks based on target Attacks on 6to4 networks. Attacks on IPv6 networks. Attacks on IPv4 networks. Attacks on the 6to4 nodes Attacks with Neighbor Discovery (ND) Messages Spoofing traffic to 6to4 nodes Reflecting traffic from 6to4 nodes Local IPv4 broadcast attack

    19 Attacks with Neighbor Discovery (ND) Messages (1/2) ND message Dst_6 (fe80::1)Src_6 (fe80::2) Dst_4 (9.0.0.2)Src_4 (8.0.0.1) forged address 6to4 pseudo-interface

    20 Attacks with Neighbor Discovery (ND) Messages (2/2) MITIGATION METHODS The usage of ND messages could be prohibited It would prohibit any sort of ND message and thus close the doors on development and use of other ND options The 6to4 pseudo-interface could be insulated from the other interfaces using a separate neighbor cache If ND messages are needed either IPsec or an extension of SEND could be used to secure packet exchange using the link-local address

    21 Spoofing traffic to 6to4 nodes (1/3) The attacker — a malicious IPv4 or IPv6 node can send packets that are difficult to trace to a 6to4 node 2001:db8::1 9.0.0.2 Spoofed Address Who!? 8.0.0.1

    22 Spoofing traffic to 6to4 nodes (2/3) EXTENSIONS — Reflection DoS 9.0.0.2 2001:db8::1 Spoofed Address 8.0.0.1 2001:db8::2 2001:db8::1 TCP SYN ACK, TCP RST, ICMPv6 Echo Reply, input sent to UDP echo service, ICMPv6 Destination Unreachable …

    23 Spoofing traffic to 6to4 nodes (3/3) MITIGATION METHODS Ingress filtering in the native IPv6 networks to prevent packets with spoofed IPv6 sources from being transmitted Unfortunately, it would depend on significant (or even complete) ingress filtering everywhere in other networks Security checks in the 6to4 relay This has very little cost

    24 Reflecting Traffic to 6to4 nodes (1/3) Reflection DoS Spoof source Traffic off target node Relay router seem to be a attacker

    25 Reflecting Traffic to 6to4 nodes (2/3) EXTENSIONS — distributed Reflection DoS A large number of nodes are involved in sending spoofed traffic with the same src_v6

    26 Spoofing traffic to 6to4 nodes (3/3) MITIGATION METHODS Implementation of ingress filtering by the IPv4 service providers Distributed Reflection DoS Legitimate user to be a illegitimate user Many IPv4 service providers don’t implement Implementation of ingress filtering by all IPv6 Expecting this to happen may not be practical Security Checks It would eliminate an attack launched from an IPv4 node, except when the IPv4 source address was also spoofed Rate limiting traffic at the 6to4 relays

    27 Local IPv4 broadcast attack (1/5) First kind of attack 2002:0900:00ff::bbbb If 9.0.0.255 is the router’s broadcast address

    28 Local IPv4 broadcast attack (2/5) First kind of attack Broadcast!Response!

    29 Local IPv4 broadcast attack (3/5) Second kind of attack 2002:0900:00ff::bbbb

    30 Local IPv4 broadcast attack (4/5) Second kind of attack Broadcast!

    31 Local IPv4 broadcast attack (5/5) Second kind of attack The attack is based on the premise that the 6to4 router has to send a packet that embeds an invalid IPv4 address to an IPv6 address Such an attack is easily thwarted by ensuring that the 6to4 router does not transmit packets to invalid IPv4 addresses. Specifically, traffic should not be sent to broadcast or multicast IPv4 addresses

    Security Cons >

    This page is designed to cover the security aspects of an OpenNMS installation. Since OpenNMS theorically has views into your entire network, keeping that information safe is very important.

    Contents

    Overview

    Most users of OpenNMS put the application on a dedicated server. While mainly for performance reasons, it is also a good idea for keeping the system secure. The less software you have installed, the less chance that a vulnerability will be discovered or exploited.

    That is also why it is a best practice to install OpenNMS on a minimal install of the operating system. The default install of many popular O/S’s can contain a number of unnecessary applications, especially if you use the desktop version, and not only do these take up disk space, they present a possible attack vector. If you install the minimal O/S of your choice and then follow the Tutorial Installation page, the installation process will install any missing packages.

    As with any application, limiting access to the system it is running on is a good first step for security. Only people that need shell access should have it.

    The main method for limiting external access to the system is by using a server-level firewall. For a fairly exhaustive list of TCP and UDP ports and ICMP datagram types that OpenNMS uses, see Firewall Policy and OpenNMS. While that page is pretty verbose, you can get away with most installs with just ports 22 (ssh), 162 (SNMP traps) and port 8980 (webUI) open. Tighter security is available if you configure the webUI to use SSL. Then you can disable external access to 8980 and replace it with your SSL port of choice (usually 8443). Note that processes such as RTC will require access to the non-SSL port, so you will need to leave that access from the localhost.

    Reporting Possible Exploits

    If you find an issue with OpenNMS that you believe affects security, please let us know via e-mail to security@opennms.org.

    The Web Server

    Tomcat (OpenNMS 1.0.0 to 1.6.0)

    This page is obsolete. Please see Jetty instead.

    Jetty has replaced Tomcat as the default servlet container for OpenNMS including situations where you run the web UI in a separate JVM. Using OpenNMS with Tomcat is no longer supported.

    By default, in its 5.5 incarnation (as used by OpenNMS 1.3.2), a standard tomcat from tomcat.apache.org will start listeners on port 8080 (http connector), 8009 (ajp13 connector) and 8005 (shutdown service). The shutdown service binds directly to the loopback address, so we can effectively ignore this.

    ajp13 8009

    The ajp connector is only required if you intend to connect to tomcat via ajp13 from apache using mod_jk, mod_jk2 or mod_proxy. Most installations will be happy to turn this off by commenting it out. The configuration directives are found in $TOMCAT_HOME/conf/server.xml thus:

    You will need comment these out in the usual way and restart tomcat for this to take effect.

    http 8080

    In order to restrict access to tomcat’s applications, you can use it’s remote address filter. For simplicity’s sake, it’s probably best to configure this at the highest (Engine) level within tomcat’s configuration heriarchy, for example, just under the default Engine configuration:

    Jetty (OpenNMS 1.8.0 and above)

    All recent versions of OpenNMS (1.8.0+) use Jetty as their web server for the web UI and REST interfaces.

    HTTP and AJP

    By default, Jetty runs HTTP on port 8980 and can also run the AJP protocol on port 8981 so these are the ports that should be protected with firewall rules. If you wish to run Jetty on an alternate port, change the following values in the opennms.properties file. You can also change the local interface that Jetty will bind to. By default, it will bind to all IP interfaces.

    HTTPS

    If Jetty is configured to use HTTPS then this will open an additional port that can also be configured inside opennms.properties . The default port is 8443. The interface that the HTTPS interface binds to can also be configured. Just like HTTP, HTTPS defaults to listening on all IP interfaces.

    The RTC User

    OpenNMS employs a Real-Time Console that allows the opennms daemon to communicate network status updates with the front-end servlet engine in near-real-time. Since all of the servlets are protected by a realm module, the opennms daemon must authenticate to the servlets. A special user, rtc was created for this purpose. In the default configuration, though, it is insecure.

    By default, all OpenNMS users are part of the OpenNMS User role. This includes the rtc users. Since the default password for the rtc user is simply rtc, this means anyone who knows this information and has the ability to contact your OpenNMS installation can log in with this user and view your OpenNMS installation. The information contained in your OpenNMS installation is likely not public knowledge and should not be viewable by non-staff. Now, in all fairness, your OpenNMS installation should be protected from the Internet at large if at all possible, but you may have need for it to face the Internet, or you may have internal users who can get to your installation but should not be able to log in.

    Lucky for us, changing the password, and even the username, for the rtc user is an easy task. The first place to change this information for versions 1.3.6 and older is the web.xml deployer file. Find the RTC Subscription parameters section in the web.xml file and change it to be the following:

    Set the RTCUSER to your rtc user’s username. Next, set the RTCPASSWORD to your chosen password.

    For versions 1.3.7 and newer, change the rtc username and password in the file WEB-INF/configuration.properties if you use Tomcat, or in the file etc/opennms.properties if you use jetty.

    If you change the rtc username, you must make sure the new username is a member of the OpenNMS RTC Daemon role in the etc/magic-users.properties file. Find the lines

    and change RTCUSER to your new rtc user name.

    If you’re using LDAP Authentication, then you’re done. Just make sure the password for the rtc user in your LDAP directory matches what you set above. If you’re using the default OpenNMS realm module, you need tt make some additional changes to the magic-users.properties file in the OpenNMS configuration directory (/opt/OpenNMS/etc in the Linux RPMs).

    If you changed the rtc username as described above, you need to change it in the magic-users.properties file as well. In addition, you’ll need to change the rtc password in this file. Find the lines below and make the appropriate changes:

    Change all instances of RTCUSER to your new rtc user name you set above, and change the RTCPASSWORD to the same password you set above.

    That’s it. Restart OpenNMS and Tomcat (if you’re using it), and you’re done.

    HTTP Security Considerations – An Introduction To HTTP Basics

    HTTP is ubiquitous now with pretty much everything being powered by an API, a web application or some kind of cloud-based HTTP driven infrastructure. With that HTTP Security becomes paramount and to secure HTTP you have to understand it.

    HTTP is the protocol that powers the web and to penetrate via a web service it pays to have a good solid foundational understanding of HTTP, how it works and the common response codes – many of which can lead to some kind of vulnerability which is exploitable.

    The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, and hypermedia information systems.[1] HTTP is the foundation of data communication for the World Wide Web.

    Hypertext is structured text that uses logical links (hyperlinks) between nodes containing text. HTTP is the protocol to exchange or transfer hypertext.

    Development of HTTP was initiated by Tim Berners-Lee at CERN in 1989. Standards development of HTTP was coordinated by the Internet Engineering Task Force (IETF) and the World Wide Web Consortium (W3C), culminating in the publication of a series of Requests for Comments (RFCs). The first definition of HTTP/1.1, the version of HTTP in common use, occurred in RFC 2068 in 1997, although this was made obsolete by RFC 2616 in 1999 and then again by the RFC 7230 family of RFCs in 2014.

    From a security perspective it’s important to understand:

    – Requests
    – Request methods
    – Responses
    – Response status codes

    All of which are covered in the Security-focused HTTP article by Acunetix.

    You can find the article with the full details here:

    Security considerations / rfc 2068

    This document describes a file format for Internet fax, which is a series of profiles of TIFF for facsimile. As such, it does not create any security issues not already identified in [TIFF-REG], in its use of fields as defined in [TIFF]. There are also new TIFF fields defined within this specification, but they are of a purely descriptive nature, so that no new security risks are incurred.

    Further, the encoding specified in this document does not in any way preclude the use of any Internet security protocol to encrypt, authenticate, or non-repudiate TIFF-encoded facsimile messages.

    Илон Маск рекомендует:  Break - Процедура Delphi
    Понравилась статья? Поделиться с друзьями:
    Кодинг, CSS и SQL