Preventing XSS Attacks with Content Security Policy (CSP)

Preventing XSS Attacks with Content Security Policy (CSP)

Daily short news for you
  • For over a week now, I haven't posted anything, not because I have nothing to write about, but because I'm looking for ways to distribute more valuable content in this rapidly exploding AI era.

    As I shared earlier this year, the number of visitors to my blog is gradually declining. When I looked at the statistics, the number of users in the first six months of 2025 has dropped by 30% compared to the same period last year, and by 15% compared to the last six months of 2024. This indicates a reality that users are gradually leaving. What is the reason for this?

    I think the biggest reason is that user habits have changed. They primarily discover the blog through search engines, with Google being the largest. Almost half of the users return to the blog without going through the search step. This is a positive signal, but it's still not enough to increase the number of new users. Not to mention that now, Google has launched the AI Search Labs feature, which means AI displays summarized content when users search, further reducing the likelihood of users accessing the website. Interestingly, when Search Labs was introduced, English articles have taken over the rankings for the most accessed content.

    My articles are usually very long, sometimes reaching up to 2000 words. Writing such an article takes a lot of time. It's normal for many articles to go unread. I know and accept this because not everyone encounters the issues being discussed. For me, writing is a way to cultivate patience and thoughtfulness. Being able to help someone through my writing is a wonderful thing.

    Therefore, I am thinking of focusing on shorter and medium-length content to be able to write more. Long content will only be used when I want to write in detail or delve deeply into a particular topic. So, I am looking for ways to redesign the blog. Everyone, please stay tuned! 😄

    » Read more
  • CloudFlare has introduced the pay per crawl feature to charge for each time AI "crawls" data from your website. What does that mean 🤔?

    The purpose of SEO is to help search engines see the website. When users search for relevant content, your website appears in the search results. This is almost a win-win situation where Google helps more people discover your site, and in return, Google gets more users.

    Now, the game with AI Agents is different. AI Agents have to actively seek out information sources and conveniently "crawl" your data, then mix it up or do something with it that we can't even know. So this is almost a game that benefits only one side 🤔!?

    CloudFlare's move is to make AI Agents pay for each time they retrieve data from your website. If they don’t pay, then I won’t let them read my data. Something like that. Let’s wait a bit longer and see 🤓.

    » Read more
  • Continuing to update on the lawsuit between the Deno group and Oracle over the name JavaScript: It seems that Deno is at a disadvantage as the court has dismissed the Deno group's complaint. However, in August, they (Oracle) must be held accountable for each reason, acknowledging or denying the allegations presented by the Deno group in the lawsuit.

    JavaScript™ Trademark Update

    » Read more

What is CSP

Content Security Policy (CSP) is an additional security layer that helps detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data attacks. These attacks can be used for various purposes, from data theft and website defacement to distributing malware.

How CSP works

When the server responds in the header with the Content-Security-Policy tag or a <meta> tag in the HTML document like:

\<meta http-equiv="Content-Security-Policy" content="default-src 'self'"\>

the supporting browser will immediately activate user protection measures by restricting the loading and execution of resources such as Javascript, CSS, iframe, Web Worker, fonts...

For example, the <meta> tag is equivalent to setting the Content-Security-Policy attribute in the response header as:

Content-Security-Policy: default-src 'self'

the browser will only load resources if they originate from the current domain (excluding subdomains).

However, it is still best practice to respond with the Content-Security-Policy attribute in the header to activate CSP, as <meta> tags will be ignored if an attacker injects code in front. Furthermore, some policy tags do not work with <meta>.

Setting policies

By setting policy tags together, you can create a comprehensive policy for your website. There are many policy tags to choose from, such as default-src or script-src to prevent inline code execution or eval(), default-src or style-src to restrict the application of styles from <style> tags or inline style attributes.

You can view the complete list of policy tags at Content-Security-Policy header.

Examples:

Only load content from the current domain and subdomains:

Content-Security-Policy: default-src 'self' example.com *.example.com

Load images from any source, restrict loading of videos or audios, and script files:

Content-Security-Policy: default-src 'self'; img-src *; media-src example.org example.net; script-src userscripts.example.com

Configuration reporting

Reporting configuration helps us detect attempts to attack the website. By setting the report-uri tag in the Content-Security-Policy attribute along with the report URI, the browser will automatically send a POST request to that address with the detailed information about the attack in the request body.

For example, the Content-Security-Policy attribute is defined as:

Content-Security-Policy: default-src 'none'; style-src cdn.example.com; report-uri http://reportcollector.example.com/collector.cgi

Create an HTML file:

<!DOCTYPE html>
<html>
  <head>
    <title>Sign Up</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    ... Content ...  
  </body>
</html>

Clearly, href="css/style.css" violates the style-src cdn.example.com policy. So if you run the html file in the browser, it will send a POST request to the report-uri with the following content:

{
  "csp-report": {
    "document-uri": "http://example.com/signup.html",  
    "referrer": "",  
    "blocked-uri": "http://example.com/css/style.css",  
    "violated-directive": "style-src cdn.example.com",  
    "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri http://reportcollector.example.com/collector.cgi"
  }
}

Conclusion

Content Security Policy is a solution to prevent XSS attacks and other types of attacks, such as clickjacking and code injection, that target the execution of malicious content within the context of a website. It works by loading and executing resources only from explicitly defined sources through the Content-Security-Policy response header or the <meta> tag in the HTML code.

References:

Premium
Hello

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (2)

Leave a comment...
Avatar
Ẩn danh1 year ago

cho minh hoi ngu xíu.*** Khi dùng script từ bên ngoài thì phài set vào CSP ***khi trang web của mình bị hack thì thôi..... còn khi trang web bên ngoài bị hack thì nó sẽ bi add mã độc vào. web mình vần down về và chạy mã đó. vậy CSP có còn hữu ích ko?

Reply
Avatar
Xuân Hoài Tống1 year ago

Thắc mắc của bạn cũng là vấn đề chung của rất nhiều người lâu nay. Có một nguyên tắc là đừng bao giờ tin hoàn toàn vào bên thứ 3, chưa nói đến việc kẻ tấn công có thể hack vào hệ thống đó hay không mà đôi khi chính nhà phát triển thư viện cũng có khả năng là kẻ tấn công.Bạn có thể tìm thấy nhiều vụ tấn công liên quan đến việc sử dụng thư viện của bên thứ 3 trên mạng Internet. Rất nhiều cảnh báo được đưa ra. Nhiều dự án chỉ sử dụng tài nguyên trên chính hệ thống của mình bằng việc tự lưu trữ lại toàn bộ script...Nhưng thế là chưa đủ, nhiều vấn đề phát sinh như tốc độ, khả năng cập nhật... rồi chưa kể thư viện thứ 3 cần phải mở thêm kết nối bên ngoài khác nữa...Nói tóm lại, sử dụng thư viện thứ 3 đồng nghĩa với việc bạn chấp nhận rủi ro một phần, vì thế hãy lựa chọn thư viện "chính chủ", uy tín... Nếu bên thứ 3 bị hack, rõ ràng là lúc này CSP cũng không chống lại được gì vì bạn đã "trust" cho tất cả tài nguyên của bên đó rồi.

Avatar
Ẩn danh1 year ago

ý mình là CSP nó có thật sự cần thiết ko?

Avatar
Xuân Hoài Tống1 year ago

Àh, mình cũng có giải thích ở câu trả lời bên dưới rồi: "Nếu bên thứ 3 bị hack, rõ ràng là lúc này CSP cũng không chống lại được gì vì bạn đã "trust" cho tất cả tài nguyên của bên đó rồi."

Avatar
Ẩn danh1 year ago

ok. cam on ban.Theo minh thay thi ban ko dam nhan CSP la that su ko can thiet.theo minh thi no ko can thiet that.tai vi neu khong dung script ben thu 3. thi van phai dung 'self'mà 'self' thi hacker vẫn lừa bạn cài extention duoc. rồi extension vẫn chạy script ok.

Avatar
Xuân Hoài Tống1 year ago

Mình nghĩ việc cài đặt extension đã là chấp nhận một phần rủi ro rồi. Nó có thể can thiệp sâu vào trang web để từ đó đánh cắp hoặc tự ý thực thi mã không được phép.Mình không dám khẳng định CSP là không hiệu quả. Ngoài kia có rất nhiều trường hợp cần phải có CSP mà không lường hết được. Một công cụ được tạo ra chắc chắn phải được sử dụng để giải quyết vấn đề nào đó. Điều đó phụ thuộc nhiều vào bài toán cần giải quyết. Bạn thấy đấy, trang web của mình hiện tại không áp dụng CSP đơn giản là do thấy chưa cần thiết.

Avatar
Nguyễn Quang Tú2 years ago

Giống với cors rồi

Reply
Avatar
Xuân Hoài Tống2 years ago

Không giống đâu bạn, bạn có thể tìm đọc các bài viết nói về sự khác nhau giữ CORS và CSP nhưng đại loại là CORS cho phép một trang web thực hiện một request đến trang khác mà được phép sử dụng cả session, cookie... của trang đó. Còn CSP cho phép một trang web ngăn chính nó tải nội dung (có khả năng độc hại) như là các tập js, css... từ các nguồn không mong muốn (như một biện pháp bảo vệ chống lại XSS)