Home  >  Article  >  Web Front-end  >  How does Content Security Policy (CSP) protect websites from malicious code injections?

How does Content Security Policy (CSP) protect websites from malicious code injections?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 11:20:02633browse

How does Content Security Policy (CSP) protect websites from malicious code injections?

Understanding Content Security Policy (CSP)

Often encountered errors in the developer console, such as "Refused to...", are a consequence of Content Security Policy (CSP), a security measure that restricts the loading of resources from untrusted sources.

How does CSP Work?

CSP enables you to control where resources can be loaded from. You define allowed sources through directives in the HTTP header Content-Security-Policy. By setting these restrictions, you minimize the risk of malicious code injections like XSS attacks.

Directives

Common directives include:

  • default-src: Default policy for loading various resources.
  • script-src: Defines valid sources for JavaScript files.
  • style-src: Defines valid sources for CSS files.
  • img-src: Defines valid sources for images.
  • connect-src: Defines valid targets for AJAX requests or WebSocket connections.

Using CSP

1. Allow Multiple Sources:

content="default-src 'self' https://example.com/js/"

2. Define Multiple Directives:

content="default-src 'self' https://example.com/js/; style-src 'self'"

3. Handling Ports:

content="default-src 'self' https://example.com:123/free/stuff/"

4. Handling Different Protocols:

content="default-src 'self'; connect-src ws:; style-src 'self'"

5. Allowing File Protocol:

content="default-src filesystem"

6. Inline Styles and Scripts:

content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"

7. Allowing eval():

content="script-src 'unsafe-eval'"

8. Meaning of 'self':
'self' refers to sources with the same scheme, host, and port as the file where the policy is defined.

9. Wildcard Warning:
While tempting, using content="default-src *" allows certain risky actions like allowing inline scripts and eval(). For true vulnerability, consider:

content="default-src * 'unsafe-inline' 'unsafe-eval'"

Resources

  • content-security-policy.com
  • en.wikipedia.org/wiki/Content_Security_Policy

The above is the detailed content of How does Content Security Policy (CSP) protect websites from malicious code injections?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn