March 2010 April 2010 May 2010 June 2010 July 2010
August 2010
September 2010 October 2010
November 2010
December 2010 January 2011 February 2011 March 2011 April 2011 May 2011 June 2011 July 2011 August 2011 September 2011 October 2011 November 2011 December 2011 January 2012 February 2012 March 2012 April 2012 May 2012 June 2012 July 2012 August 2012 September 2012 October 2012 November 2012 December 2012 January 2013 February 2013 March 2013 April 2013 May 2013 June 2013 July 2013 August 2013 September 2013 October 2013 November 2013 December 2013 January 2014 February 2014 March 2014 April 2014 May 2014 June 2014 July 2014 August 2014 September 2014 October 2014 November 2014 December 2014 January 2015 February 2015 March 2015 April 2015 May 2015 June 2015 July 2015 August 2015 September 2015 October 2015 November 2015 December 2015 January 2016 February 2016 March 2016 April 2016 May 2016 June 2016 July 2016 August 2016 September 2016 October 2016 November 2016 December 2016 January 2017 February 2017 March 2017 April 2017 May 2017 June 2017 July 2017 August 2017 September 2017 October 2017 November 2017 December 2017 January 2018 February 2018 March 2018 April 2018 May 2018 June 2018 July 2018 August 2018 September 2018 October 2018 November 2018 December 2018 January 2019 February 2019 March 2019 April 2019 May 2019 June 2019 July 2019 August 2019 September 2019 October 2019 November 2019 December 2019 January 2020 February 2020 March 2020 April 2020 May 2020 June 2020 July 2020 August 2020 September 2020 October 2020 November 2020 December 2020 January 2021 February 2021 March 2021 April 2021 May 2021 June 2021 July 2021 August 2021 September 2021 October 2021 November 2021 December 2021 January 2022 February 2022 March 2022 April 2022 May 2022 June 2022 July 2022 August 2022 September 2022 October 2022 November 2022 December 2022 January 2023 February 2023 March 2023 April 2023 May 2023 June 2023 July 2023 August 2023 September 2023 October 2023 November 2023 December 2023 January 2024 February 2024 March 2024 April 2024 May 2024 June 2024 July 2024 August 2024 September 2024 October 2024 November 2024
1 2 3 4 5 6 7 8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
News Every Day |

Your Guide to Content Security Policy

Your Guide to Content Security Policy

What is Content Security Policy (CSP)?

A Content Security Policy (CSP) is a security feature implemented in web applications to protect against a range of attacks, particularly cross-site scripting (XSS), data injection, and clickjacking. It works by allowing web developers to specify which sources of content (e.g., scripts, styles, images) are considered safe for their website. 

Why is Content Security Policy important? 

CSPs help reduce the risk of cross-site scripting attacks, clickjacking, data injection, and packet sniffing. While it’s possible to mitigate many of these attacks in other ways, like sanitizing user input and redirecting insecure requests to the HTTPS version of the website, setting a secure CSP provides an additional layer of defense.

CSP protects against a wide variety of attacks, including some malicious browser extensions designed to inject code. The attacks a CSP can guard against are simple to execute—but they can be incredibly damaging. 

In an ideal world, malicious extensions would never make it to the marketplace. However, since dangerous extensions do exist, setting a strict Content Security Policy serves as a safeguard to prevent inline code from running.

XSS attacks affect businesses of all sizes. British Airways once fell victim to an XSS vulnerability in the Feedify JavaScript library. Attackers took advantage of that vulnerability and were able to skim credit card data for 380,000 transactions before the breach was discovered.

Content security policies can’t prevent all attacks. They’re enforced by the browser and sophisticated users can override them. However, they go a long way toward protecting the average end-user.

Common threats

Let’s consider some common threats and how they can impact your users:

Cross-site scripting (XSS)

With XSS, a common vulnerability, malicious scripts are injected into trusted websites with the intent of stealing a cookie/session token or tricking the user into taking an action. XSS attacks are easy to carry out and can be highly destructive. Because of this, malicious actors often use automated scanning tools to find vulnerable websites.

Clickjacking

Clickjacking attacks involve embedding invisible (or disguised) HTML elements into a page, tricking the user into clicking a malicious link. To give a relatively benign example, an attacker might manipulate the layout of a page to fool someone into thinking they’re “liking” a specific Facebook page when the link leads to a different one.

Data injection

Malicious actors use data injection attacks to fool systems into executing malicious code. XSS attacks are a form of data injection. HTTP header injections and SQL injections are also of concern to developers. There are many types of data injection attacks, and CSPs can only protect against some of them, so it’s essential to have other safeguards in place.

How does Content Security Policy work?

Developers can set a Content-Security-Policy header, which gets sent to the browser when a user accesses a web page. This policy tells the browser where certain content types, such as JavaScript, CSS, fonts, and embeddable objects, can be loaded from. It’s also possible to define the Content-Security-Policy in a meta tag.

The CSP can also help reduce the risk of packet sniffing attacks by dictating the protocols that can be used to transfer data. When used in conjunction with the Strict-Transport-Security response header and redirecting HTTP requests to HTTPS instead, it’s possible to block unencrypted data transfers.

The Content Security Policy contains a set of directives that serve as an allow-list for specific types of content. It’s good practice to set a strict default-src directive as a fallback, which the browser will treat as the default security policy if there isn’t a more specific applicable rule.

For example, if a web developer wants to ensure all content gets loaded from the same host, port, and protocol as the original page, they’d use the declaration of:

Copy Code
Content-Security-Policy: default-src 'self';

However, as the site grows more complex, the developer may find themselves using scripts hosted on third-party sites and decide to permit them explicitly:

Copy Code
Content-Security-Policy: default-src ‘self’; script-src ‘self’ coolscripts.example.com;

A Content Security Policy can cover images, videos, and iframes. The CSP listed above would prevent embedded YouTube videos from loading. To permit them, set the frame-src:

Copy Code
Content-Security-Policy: frame-src youtube.com www.youtube.com;

While setting default-src is considered best practice, it’s not mandatory. If there’s no default-src set, the browser will fall back to its default handling rules. These rules can vary dramatically depending on the browser, making the user experience unpredictable.

CSPs can also prevent inline scripts from running, which provides a valuable extra layer of protection against malicious content submitted by users (on websites that permit user posts or comments, for example). This is the default behavior unless you include the unsafe-inline value.

You can also configure your CSP to report violations. This data can then be fed into a SIEM tool to alert you to malicious attacks and potential errors in your CSP that may be degrading the end-user experience.

Copy Code
Reporting-Endpoints: csp-endpoint="https://example.com/report-csp-violation"

Content Security Policy best practices

A carefully defined CSP can significantly improve the security of your web application. For optimal results, keep the following best practices in mind when defining a CSP:

  • Use default-src to catch edge cases, and set this directive to be as restrictive as possible, ideally just ‘self’.
  • Avoid unsafe-inline and unsafe-eval, as they significantly reduce the effectiveness of your CSP.
  • Use restrictive settings, and only allow the hosts and protocols you actively need.
  • Avoid “*” wildcards, perhaps with the exception of permitting subdomains of domains you control.

Nonces

If you want to permit the use of inline styles or JavaScript, you can make it more secure by using a nonce. Nonces are unique strings generated each time a page is requested. They can be added to the CSP header/tag and the attributes of the relevant inline tags.

The browser will only apply the CSS or execute the JavaScript if the nonce in the CSS/javascript matches the one in the CSP.

Simply define the following in your CSP:

Copy Code
Content-Security-Policy: script-src ‘nonce-cE3Iu9HEt745’;

Then, use the nonce in your scripts:

Copy Code
<script nonce=’cE3Iu9HEt745’>
	thisWillRun();
</script>

<script>
	thisHasNoNonceSoWillNotRun();
</script>

WordPress provides the wp_create_nonce() function, which can generate a nonce each time a page loads for inclusion in the Content Security Policy header or meta tag. We offer expert guidance on ensuring that any inline scripts added to your site include the nonce correctly.

For example, we can help with custom development support and security audits to help your team implement nonces securely and in line with best practices.  We also often work directly with your development team to ensure compliance with CSP requirements and maintain strong site security.

Testing your security policy

When implementing a Content Security Policy, developers often overlook certain content types or trusted remote hosts. A policy that’s too restrictive can result in unexpected behaviors that degrade the user experience.

To reduce the risk of problems when rolling out a new CSP or changes to your existing CSP, use the report-only mode to test the policy before setting it live. This mode will trigger a report whenever the CSP gets violated, but the user will still be able to navigate and interact with the website as normal.

CSP violation reports are sent as a POST request in JSON format:

Copy Code
{
  "csp-report": {
    "blocked-uri": "http://malicious-site.example.com/keylogger.js",
    "disposition": "report",
    "document-uri": "http://example.com/login.html",
    "effective-directive": "script-src-elem",
    "original-policy": "default-src 'none'; script-src ajax.googleapis.com; report-uri /_/csp-reports",
    "referrer":"  ",
    "status-code": 200,
    "violated-directive": "script-src-elem"
  }
}

Any website that generates even a moderate amount of traffic will probably see a lot of CSP violation reports. However, most will be generated by automated scripts looking for vulnerable websites.

To help parse the reports, it’s a good idea to use a tool such as Sentry or DataDog. These cloud services can capture reports and provide a dashboard for filtering and generating visualizations. 

Once you’re satisfied that your Content Security Policy isn’t flagging any false positives, you can remove the report-only flag and set it live.

Secure your WordPress website today

The Content Security Policy header/meta tag is an important security tool. WordPress developers can benefit from having a well-defined CSP because it decreases the website’s attack surface and may help guard against vulnerabilities introduced by outdated or poorly coded plugins and themes. If you want to know more about how WordPress VIP can help you improve your WordPress Security or need assistance with defining your CSP, contact us today to book a consultation.

Москва

Врач Кондрахин рассказал, смертелен ли вирус Коксаки

‘We do not get to sit this one out’: Oprah delivers powerful election eve speech

GREG GUTFELD: We may not get this country back on its feet tomorrow, but we're well on our way

Karkala MLA slams Karnataka govt for failing to fund plank installations on Udupi dams

Karachi industrial park to be declared model special economic zone

Ria.city






Read also

'You know how this works, right?' Madigan jurors hear longtime ally complaining to speaker's son

Timberwolves vs. Bulls: How to watch online, live stream info, game time, TV channel | November 7

Drake Maye Already Does This At Elite Level Compared To NFL QBs

News, articles, comments, with a minute-by-minute update, now on Today24.pro

News Every Day

Karkala MLA slams Karnataka govt for failing to fund plank installations on Udupi dams

Today24.pro — latest news 24/7. You can add your news instantly now — here


News Every Day

Karkala MLA slams Karnataka govt for failing to fund plank installations on Udupi dams



Sports today


Новости тенниса
WTA

Касаткина сыграет на Итоговом турнире WTA после снятия Пегулы



Спорт в России и мире
Москва

«ЦВБП-медиа»: на шоу Навки над эмблемой ХК «Спартак» появилась свиная голова



All sports news today





Sports in Russia today

Москва

Экс-президент США признал ошибку, которая продолжается до сих пор: МОК превратился в цирк


Новости России

Game News

Meta-funded regulator for AI disinformation on Meta's platform comes under fire: 'You are not any sort of check and balance, you are merely a bit of PR spin'


Russian.city


Москва

В России вновь пройдет культурно-благотворительный фестиваль детского творчества «Добрая волна»


Губернаторы России
Кубок

Кубок Ил Дархана: Будет яркое шоу, в лучших традициях Якутии


ДЕЛО КАМАЛЫ ХАРРИС МОГЛИ ПЕРЕСЕЧЬ С ДЕЛОМ КАМИЛЫ ВАЛИЕВОЙ. Россия, США, Европа могут улучшить отношения и здоровье общества?! Дональд Трамп, Владимир Путин, выборы в Америке.

Джиган, Artik & Asti и NILETTO спели о худи, а Дина Саева стала новым артистом: в Москве прошел BRUNCH Rocket Group

Ты на свете одна! Певица Дэя выпустила клип на песню «Россия»

Как 83 года назад. На Красной площади воссоздали военный парад 1941 года


В России вновь пройдет культурно-благотворительный фестиваль детского творчества «Добрая волна»

Авраам Руссо требует от своего похитителя 5,7 млн рублей компенсации

Баста приостановил концерт в Красноярске ради зрительницы, которой стало плохо

«Мальчик из подвала»: малоизвестные факты об Александре Градском


Российская теннисистка Анастасия Потапова сообщила о разводе

Теннисистка Пегула снялась с итогового турнира WTA, ее заменит Касаткина

Медведев обошел Джоковича в рейтинге АТР

Касаткина сыграет на Итоговом турнире WTA после снятия Пегулы



В России вновь пройдет культурно-благотворительный фестиваль детского творчества «Добрая волна»

В России вновь пройдет культурно-благотворительный фестиваль детского творчества «Добрая волна»

С начала 2024 года Отделение СФР по Москве и Московской области оплатило пособия по временной нетрудоспособности 2,9 млн жителей региона

Соколова по указу Путина наградили орденом Александра Невского


Ирина Роднина: «Фильмы о спорте имеют фантастический воспитательный эффект»

Богданов борется за сердце Glukozы, а Хрусталев ищет кольцо Нефертити

Что лечит врач-проктолог у женщин и мужчин?

Десятков — о поражении «Витязя» от «Динамо»: «Если мы профессионалы, то мы должны выходить и отвечать»


Эксперт бренда бытовой техники HYUNDAI рассказал о новинках 2024 года

АРМЕНИЯ. Сергей Шойгу: региональным проблемам Южного Кавказа нужны региональные решения

Трамп ответил на сигнал Путина: "Мы поговорим"

Казбек Коков и Евгений Янкилевич обсудили перспективы развития международного аэропорта «Нальчик»



Путин в России и мире






Персональные новости Russian.city
Анастасия Волочкова

Телеведущая Елена Николаева опубликовала свадебные фото с экс-мужем Волочковой



News Every Day

Karachi industrial park to be declared model special economic zone




Friends of Today24

Музыкальные новости

Персональные новости