Preventing XSS Attacks with Content Security Policy (CSP)

Preventing XSS Attacks with Content Security Policy (CSP)

Daily short news for you
  • Thank you to threads.net from Meta for being the inspiration behind this section on my blog. Initially, I was a bit skeptical about whether creating short posts like this would attract users, whether anyone would come back to read day after day, or if it would all just be like building sandcastles by the sea. As I have often mentioned, creating a feature is not difficult, but how to operate it effectively is what truly matters.

    Now, time has proven everything. The Short Posts section consistently ranks in the top 5 most visited pages of the day/week/month. This means that readers have developed a habit of returning more often. How can I be so sure? Because this section is almost completely unoptimized for SEO on search engines like Google.

    Let me take you back a bit. In the beginning, I was very diligent in posting on threads.net in the hope of attracting many followers, so that I could subtly introduce them to become users of my blog. However, as time went on, I increasingly felt "exhausted" because the Threads algorithm became less and less aligned with my direction. In other words, the content created was not popular.

    For example, my posts often lean towards sharing information, news, or personal experiences drawn from learning or doing something. It seems that such posts are not highly regarded and often get buried after just over... 100 views. Hmm... Could the problem be me? Knowing this, why not change the content to be more suitable for the platform?

    I have observed Threads, and the content that spreads the most easily often contains controversial elements or a prejudice about something, sometimes it’s simply stating something "naively" that they know will definitely get interactions. However, I almost do not like directing users towards this kind of content. People might call me stubborn, and I accept that. Everyone has different content directions and audiences; the choice is theirs.

    So, from then on, I mainly write here. Only occasionally, if I find something very interesting, do I go on Threads to "show off." Here, people still come to read daily; no matter who you are, I am sure that you can recognize the message I want to convey through each post. At the very least, we share a common direction regarding content. Sometimes, the scariest thing is not that no one reads what you write, but that they read it and then forget it in an instant. Quantity is important, but quality is what brings us closer together.

    Thank you all 🤓

    » Read more
  • Zed is probably the most user-centric developer community on the planet. Recently, they added an option to disable all AI features in Zed. While many others are looking to integrate deeper and do more with AI Agents. Truly a bold move 🤔

    You Can Now Disable All AI Features in Zed

    » Read more
  • Today I have tried to walk a full 8k steps in one session to show you all. As expected, the time spent walking reached over 1 hour and the distance was around 6km 🤓

    Oh, in a few days it will be the end of the month, which means it will also mark one month since I started the habit of walking every day with the goal of 8k steps. At the beginning of next month, I will summarize and see how it goes.

    » 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 danh2 years 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ống2 years 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 danh2 years ago

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

Avatar
Xuân Hoài Tống2 years 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 danh2 years 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ống2 years 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ú3 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)