网络安全

网站包含几种不同类型的信息。其中一些是非敏感的,例如公共页面上显示的副本。其中一些是敏感的,例如客户用户名、密码和银行信息,或内部算法和私有产品信息。

¥Websites contain several different types of information. Some of it is non-sensitive, for example the copy shown on the public pages. Some of it is sensitive, for example customer usernames, passwords, and banking information, or internal algorithms and private product information.

敏感信息需要受到保护,这是网络安全的重点。如果该信息落入坏人之手,它可以用于:

¥Sensitive information needs to be protected, and that is the focus of web security. If that information fell into the wrong hands, it could be used to:

  • 与竞争对手共享信息会使公司处于竞争劣势。
  • 禁用或劫持他们的服务,再次导致他们的操作出现严重问题。
  • 将客户的 privacy 置于风险之中,使他们容易受到分析、定位、数据丢失、身份被盗,甚至经济损失。

现代浏览器已经具备多种功能来保护用户的网络安全,但开发者还需要仔细采用最佳实践和代码来确保其网站的安全。即使代码中的简单错误也可能导致漏洞,坏人可以利用这些漏洞窃取数据并控制他们没有授权的服务。

¥Modern browsers already have several features to protect users' security on the web, but developers also need to employ best practices and code carefully to ensure that their websites are secure. Even simple bugs in your code can result in vulnerabilities that bad people can exploit to steal data and gain control over services for which they don't have authorization.

本文介绍了网络安全,包括帮助你了解可能使网站容易受到攻击的方面以及如何保护网站安全的信息。

¥This article provides an introduction to web security, including information that will help you understand the aspects that can make websites vulnerable and how to secure them.

安全与隐私的关系

¥Relationship between security and privacy

安全和隐私是不同的主题,但它们也密切相关。值得了解两者之间的区别以及它们之间的关系。

¥Security and privacy are distinct topics, but they are also closely-related. It is worth knowing the difference between the two and how they relate.

  • 安全是保护私有数据和系统免受未经授权的访问的行为。这包括公司(内部)数据以及用户和合作伙伴(外部)数据。
  • 隐私是指赋予用户控制其数据如何被收集、存储和使用的权利,并且不被不负责任地使用的行为。例如,你应该清楚地向网站用户传达你正在收集的数据、将与谁共享这些数据以及将如何使用这些数据。用户必须有机会同意你的隐私政策,有权访问你存储的他们的数据,如果他们不再希望你拥有他们的数据,则可以删除他们的数据。

良好的安全性对于良好的隐私至关重要。你可以遵循我们的 网络隐私 指南中列出的所有建议,但如果你的网站不安全并且攻击者无论如何都可以窃取数据,那么诚信行事和制定健全的隐私政策都是徒劳的。

¥Good security is very essential for good privacy. You could follow all the advice listed in our Privacy on the web guide, but acting with integrity and having a robust privacy policy are futile if your site is not secure and attackers can just steal data anyway.

浏览器提供的安全服务

¥Security services provided by browsers

Web 浏览器具有严格的安全模型,可强制执行良好水平的基本内容、连接和传输安全性。本节介绍基础知识。

¥Web browsers have a strict security model that enforces a good level of fundamental content, connection, and transport security. This section looks at the basics.

同源策略和 CORS

¥Same-origin policy and CORS

同源策略 是 Web 的一种基本安全机制,它限制从 origin 加载的文档或脚本如何与另一个来源的资源进行交互。它有助于隔离潜在的恶意文档,减少可能的攻击媒介。

¥Same-origin policy is a fundamental security mechanism of the web that restricts how a document or script loaded from one origin can interact with a resource from another origin. It helps isolate potentially malicious documents, reducing possible attack vectors.

一般来说,来自一个来源的文件不能向其他来源提出请求。这是有道理的,因为你不希望站点能够相互干扰并访问它们不应该访问的内容。在某些情况下放宽这一限制确实有意义;例如,你可能有多个相互交互的站点,并且你可能希望这些站点相互请求资源,例如使用 fetch()

¥In general, documents from one origin cannot make requests to other origins. This makes sense because you don't want sites to be able to interfere with one another and access things they shouldn't. It does make sense to relax this restriction in some circumstances; for example, you might have multiple sites that interact with each other, and you may want these sites to request resources from one another, such as using fetch().

这可以使用 跨域资源共享 (CORS) 来实现,跨域资源共享 (CORS) 是一种基于 HTTP 标头的机制,允许服务器指示除其自身之外的任何来源(域、方案或端口),浏览器应允许从中加载资源。

¥This can be permitted using Cross-Origin Resource Sharing (CORS), an HTTP-header-based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

HTTP 通信模型

¥HTTP model for communication

Web 浏览器和服务器使用 HTTP 协议相互通信、请求资源、提供响应(例如,提供所请求的资源或详细说明请求失败的原因),并为该通信提供安全功能。

¥HTTP protocol is used by web browsers and servers to communicate with one another, request resources, provide responses (for example, providing the requested resource or detailing why the request failed), and provide security features for that communication.

传输层安全 (TLS) 通过在网络传输过程中对数据进行加密来提供安全性和隐私性,是 HTTPS 协议背后的技术。TLS 有利于隐私,因为它可以阻止第三方拦截传输的数据并恶意使用它。

¥Transport Layer Security (TLS) provides security and privacy by encrypting data during transport over the network and is the technology behind the HTTPS protocol. TLS is good for privacy because it stops third parties from being able to intercept transmitted data and use it maliciously.

所有浏览器都默认要求使用 HTTPS;实际上已经是这样了,因为如果没有这个协议,你就无法在网络上做很多事情。

¥All browsers are moving towards requiring HTTPS by default; this is practically the case already because you can't do much on the web without this protocol.

相关话题:

¥Related topics:

传输层安全 (TLS)

传输层安全 (TLS) 协议是使两个联网应用或设备能够私密且可靠地交换信息的标准。使用 TLS 的应用可以选择其安全参数,这会对数据的安全性和可靠性产生重大影响。本文概述了 TLS 以及保护内容时需要做出的各种决策。

HTTP 严格传输安全

Strict-Transport-Security: HTTP 标头让网站指定只能使用 HTTPS 访问它。

证书透明度

证书透明度是一个开放框架,旨在防止和监控证书误发。新颁发的证书是 'logged' 公开运行的,通常是独立的 CT 日志,它维护已颁发的 TLS 证书的仅附加的、加密保证的记录。

混合内容

包含使用明文 HTTP 获取的内容的 HTTPS 页面称为混合内容页面。像这样的页面仅部分加密,使嗅探器和中间人攻击者可以访问未加密的内容。

如何修复混合内容被阻止的网站

如果你的网站发送的是 HTTPS 页面,则这些页面上所有通过 HTTP 发送的 活性混合内容 都会被默认拦截。因此,你的网站可能会对用户造成损坏(如果 iframe 或插件无法加载等)。默认情况下显示 被动混合内容,但用户也可以设置首选项来阻止此类内容。本页解释了作为 Web 开发者应该注意的事项。

弱签名算法

signingdigital certificate 中使用的哈希算法的强度是证书安全性的关键要素。本文提供了一些有关已知较弱的签名算法的信息,因此你可以在适当的时候避免使用它们。

安全上下文和功能权限

¥Secure contexts and feature permissions

浏览器以几种不同的方式控制多个 "强大的功能" 的使用。"强大的功能" 指的是网站生成系统通知、使用用户的网络摄像头访问媒体流、操纵系统 GPU 以及使用网络支付等。如果站点可以不受限制地使用控制此类功能的 API,则恶意开发者可能会执行以下操作:

¥Browsers control usage of several "powerful features" in a few different ways. By "powerful features", we mean things like a site generating system notifications, using a user's web cam to get access to a media stream, manipulating the system GPU, and using web payments. If a site could just use the APIs that control such features without restriction, malicious developers could for example:

  • 用不需要的通知和其他 UI 功能惹恼用户。
  • 堵塞他们的浏览器/系统以发起 Denial of Service (DoS) 攻击。
  • 窃取数据或金钱。

此类浏览器功能的控制如下:

¥Such browser features are controlled as follows:

首先,仅在 安全上下文 中允许使用此类功能。安全上下文是 windowworker,有合理的信心认为内容已安全交付(通过 HTTPS/TLS)。在安全上下文中,与不安全上下文进行通信的潜力是有限的。安全上下文还有助于防止 中间人攻击者 访问浏览器的强大 API。

¥First, usage of such features is permitted only in secure contexts. A secure context is a window or a worker for which there is reasonable confidence that the content has been delivered securely (via HTTPS/TLS). In a secure context, the potential for communication with contexts that are not secure is limited. Secure contexts also help to prevent man-in-the-middle attackers from accessing the powerful APIs of the browser.

注意:另见 仅限于安全上下文的功能。此参考列出了仅在安全上下文中可用的 Web 平台功能。

¥Note: See also Features restricted to secure contexts. This reference lists web platform features available only in secure contexts.

其次,这些功能的使用受到用户权限系统的限制 - 用户必须明确选择提供对这些功能的访问,这意味着这些功能不能自动使用。用户权限请求会自动发生,但你可以使用 权限 API.API 查询 API 权限的状态。

¥Second, the usage of these features is gated behind a system of user permissions — users have to explicitly opt-in to providing access to such features, meaning that these featured can't be used automatically. The user permission requests happen automatically, but you can query the state of an API permission by using the Permissions API.

第三,许多其他浏览器功能只能用于响应用户操作(例如单击按钮),这意味着它们需要从适当的事件处理程序内部调用。这通常称为瞬时激活。请参阅 由用户激活控制的功能 了解更多信息。

¥Third, many other browser features can be used only in response to a user action such as clicking a button, meaning that they need to be invoked from inside an appropriate event handler. This is often called transient activation. See Features gated by user activation for more information.

客户端开发者的安全注意事项

¥Security considerations for client-side developers

服务器端和客户端需要考虑 Web 安全的许多方面。以下部分主要关注客户端安全注意事项。你可以在 网站安全(我们的 服务器端网站编程 学习模块的一部分)找到从服务器端角度来看的有用的安全性摘要,其中还包括需要注意的常见攻击的描述。

¥There are many aspects of web security that need to be thought about on the server- and client-side. The sections below focus mainly on client-side security considerations. You can find a useful summary of security from a server-side perspective, which also includes descriptions of common attacks to watch out for, at Website security (part of our Server-side website programming learning module).

负责任地存储客户端数据

¥Store client-side data responsibly

负责任地处理数据主要涉及减少 cookie 的使用 并小心存储在其中的数据。传统上,Web 开发者出于各种目的使用 Cookie 来存储各种数据,攻击者很容易利用这种趋势。因此,浏览器已开始限制你可以使用跨站点 cookie 执行的操作,目的是在将来完全删除对它们的访问。

¥Handling data responsibly is largely concerned with cutting down on cookie usage and being careful about the data you store in them. Traditionally, web developers have used cookies to store all kinds of data, for all kinds of purposes, and it has been easy for attackers to exploit this tendency. As a result, browsers have started to limit what you can do with cross-site cookies, with the aim of removing access to them altogether in the future.

你应该通过限制你所依赖的跟踪活动的数量和/或通过以其他方式实现所需的信息持久性来准备删除跨站点 cookie。

¥You should prepare for the removal of cross-site cookies by limiting the amount of tracking activities you rely on and/or by implementing desired information persistence in other ways.

例如:

¥For example:

  • 使用替代的客户端存储机制(例如 Web 存储 API)来保存数据。Web 存储确实有一个缺点,即数据是按源存储的,因此无法共享。请注意,网络存储有两个变体 - sessionStoragelocalStorage。我们建议使用 sessionStorage 来提高安全性,因为数据仅在其所在的窗口或选项卡的生命周期内保留。即使窗口或选项卡关闭并重新打开后,localStorage 数据仍然存在。这意味着它落入坏人之手的可能性更高,例如在共享工作站上。
  • 使用 存储访问 API 等技术允许你的站点以安全且受控的方式选择使用跨站点 cookie。
  • 使用服务器端解决方案进行数据持久化。

请参阅我们的 隐私指南,特别是 减少跟踪 cookie,了解有关此内容的更多背景信息。

¥See our privacy guide and particularly Cut down on tracking cookies for more context around this.

保护用户身份并管理登录

¥Protect user identity and manage logins

在实现涉及数据收集的安全解决方案时,特别是当数据敏感(例如登录凭据)时,使用来自备受尊敬的提供商的信誉良好的解决方案是有意义的。例如,任何受人尊敬的服务器端框架都将具有内置功能来防止常见漏洞。你还可以考虑使用专门的产品来实现你的目的,例如身份提供商解决方案或安全的在线调查提供商。

¥When implementing a secure solution that involves data collection, particularly if the data is sensitive such as log-in credentials, it makes sense to use a reputable solution from a well-respected provider. For example, any respectable server-side framework will have built-in features to protect against common vulnerabilities. You could also consider using a specialized product for your purpose, for example an identity provider solution or a secure online survey provider.

如果你想推出自己的解决方案来收集用户数据,请确保你了解所有方面和要求。聘请经验丰富的服务器端开发者和/或安全工程师来实现系统,并确保对其进行彻底的测试。使用多重身份验证 (MFA) 提供更好的保护。考虑使用专用 API(例如 网页认证联合凭证管理)来简化应用的客户端。

¥If you want to roll your own solution for collecting user data, make sure you understand all aspects and requirements. Hire an experienced server-side developer and/or security engineer to implement the system, and ensure it is tested thoroughly. Use multi-factor authentication (MFA) to provide better protection. Consider using a dedicated API such as Web Authentication or Federated Credential Management to streamline the client-side of the app.

以下是提供安全登录的一些其他提示:

¥Here are some other tips for providing secure logins:

  • 收集用户登录信息时,请强制使用强密码,以便你的用户的账户详细信息不会被轻易猜到。弱密码是安全漏洞的主要原因之一。此外,鼓励你的用户使用密码管理器,这样他们就可以使用更复杂的密码,无需担心记住密码,也不会因写下密码而产生安全风险。另请参阅我们关于 密码不安全 的文章。
  • 你还应该对用户进行有关网络钓鱼的教育。网络钓鱼是向用户发送消息(例如电子邮件或短信)的行为,其中包含看似用户每天使用的网站的链接,但实际上并非如此。该链接附带一条消息,旨在诱骗用户在网站上输入用户名和密码,以便其被窃取,然后被攻击者用于恶意目的。

    注意:一些网络钓鱼网站可能非常复杂,很难与真实网站区分开来。因此,你应该教育你的用户不要信任电子邮件和短信中的随机链接。如果他们收到类似 "紧急,你需要立即登录才能解决问题" 的消息,他们应该直接在新选项卡中转到该站点并尝试直接登录,而不是单击消息中的链接。或者他们可以给你打调用或发送电子邮件讨论他们收到的消息。

    ¥Note: Some phishing sites can be very sophisticated and hard to distinguish from a real website. You should therefore educate your users to not trust random links in emails and SMS messages. If they receive a message along the lines of "Urgent, you need to log in now to resolve an issue", they should go to the site directly in a new tab and try logging in directly rather than clicking the link in the message. Or they could phone or email you to discuss the message they received.

  • 使用 速率限制 防止对登录页面进行暴力攻击,在一定次数的不成功尝试后锁定账户,以及 验证码挑战
  • 使用唯一的 会话 ID 管理用户登录会话,并在用户不活动一段时间后自动注销。

不要在 URL 查询字符串中包含敏感数据

¥Don't include sensitive data in URL query strings

作为一般规则,你不应该 在 URL 查询字符串中包含敏感数据:如果第三方拦截 URL(例如通过 Referer HTTP 标头),他们就可以窃取该信息。更严重的是,这些 URL 可以被公共网络爬虫、HTTP 代理和 互联网档案馆 等归档工具编制索引,这意味着你的敏感数据可以保留在可公开访问的资源上。

¥As a general rule you shouldn't include sensitive data in URL query strings: if a third party intercepts the URL (for example via the Referer HTTP header), they could steal that information. Even more serious is that these URLs can be indexed by public web crawlers, HTTP proxies, and archiving tools such as the internet archive, meaning that your sensitive data can persist on publicly accessible resources.

使用 POST 请求而不是 GET 请求可以避免这些问题。我们的文章 Referer 标头策略:隐私和安全问题 更详细地描述了与 Referer 标头相关的隐私和安全风险,并提供了减轻这些风险的建议。

¥Use POST requests rather than GET requests to avoid these issues. Our article Referer header policy: Privacy and security concerns describes in more detail the privacy and security risks associated with the Referer header, and offers advice on mitigating those risks.

注意:避免通过 GET 请求传输 URL 中的敏感数据也有助于防范 cross-site request forgery重放攻击

¥Note: Steering away from transmitting sensitive data in URLs via GET requests can also help protect against cross-site request forgery and replay attacks.

执行使用政策

¥Enforce usage policies

考虑使用 内容安全政策 (CSP) 和 权限策略 等工具在站点上强制执行一组功能和资源使用,从而更难引入漏洞。

¥Consider using tools like Content Security Policy (CSP) and Permissions policy to enforce a set of feature and resource usage on your site that makes it harder to introduce vulnerabilities.

CSP 允许你添加一层安全性,例如,允许仅从特定的受信任来源加载图片或脚本。这有助于检测和减轻某些类型的攻击,包括跨站点脚本攻击 (XSS) 和数据注入攻击。这些攻击涉及一系列恶意活动,包括数据盗窃、网站篡改和恶意软件传播。

¥CSP allows you to add a layer of security by, for example, allowing images or scripts to be loaded only from specific trusted origins. This helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks involve a range of malicious activities, including data theft, site defacement, and distribution of malware.

权限策略的工作方式类似,只不过它更关注允许或阻止对特定 "强大的功能" (如前面提到的) 的访问。

¥Permissions policy works in a similar way, except that it is more concerned with allowing or blocking access to specific "powerful features" (as mentioned earlier).

注意:此类策略对于确保网站安全非常有用,尤其是当你在网站上使用大量第三方代码时。但是,请记住,如果你阻止使用第三方脚本所依赖的功能,则最终可能会破坏站点的功能。

¥Note: Such policies are very useful to help keep sites secure, especially when you are using a lot of third party code on your site. However, keep in mind that if you block usage of a feature that a third-party script relies on to work, you may end up breaking your site's functionality.

维护数据完整性

¥Maintain data integrity

继上一节之后,当你允许在站点上使用功能和资源时,你应该尝试确保资源未被篡改。

¥Following on from the previous section, when you do allow feature and resource usage on your site, you should try to ensure that resources have not been tampered with.

相关话题:

¥Related topics:

子资源完整性

子资源完整性 (SRI) 是一项安全功能,使浏览器能够验证它们获取的资源(例如,从 CDN)是否在没有意外操作的情况下交付。它的工作原理是允许你提供所获取的资源必须匹配的加密哈希。

HTTP 访问控制允许来源

Access-Control-Allow-Origin 响应标头指示是否可以与来自给定 origin 的请求代码共享该响应。

HTTP X-内容类型-选项

X-Content-Type-Options 响应 HTTP 标头是服务器使用的标记,用于指示不应更改并遵循 Content-Type 标头中通告的 MIME 类型。这是一种选择退出 MIME 类型嗅探 的方法,或者换句话说,MIME 类型是故意配置的。

清理表单输入

¥Sanitize form input

作为一般规则,不要信任用户在表单中输入的任何内容。在线填写表格复杂、繁琐,而且用户很容易输入错误的数据或格式错误的数据。此外,恶意人员非常擅长将特定的可执行代码字符串输入表单字段(例如 SQL 或 JavaScript)。如果你不小心处理这些类型的输入,它可能会在你的网站上执行有害代码或删除你的数据库。有关如何发生这种情况的一个很好的示例,请参阅 SQL 注入

¥As a general rule, don't trust anything that users enter into forms. Filling out forms online is complicated and tedious, and it is easy for users to enter wrong data or data in the wrong format. In addition, malicious folks are well-versed in the art of entering specific strings of executable code into form fields (for example, SQL or JavaScript). If you're not careful about handling these types of inputs, it could either execute harmful code on your site or delete your databases. See SQL injection for a good example of how this could happen.

为了防止这种情况,你应该彻底清理表单中输入的数据:

¥To protect against this, you should thoroughly sanitize data entered into your forms:

  • 你应该实现客户端验证,以便在用户以错误格式输入数据时通知他们。你可以使用内置的 HTML 表单验证功能来完成此操作,也可以编写自己的验证代码。请参阅 客户端表单验证 了解更多信息。
  • 在应用 UI 中显示用户输入时,你应该使用输出编码,以安全地完全按照用户键入的方式显示数据,以避免将其作为代码执行。请参阅 输出编码 了解更多信息。

但是,你不能仅依靠客户端验证来确保安全。这对于你的用户来说是一种有用的用户体验增强,因为它可以为他们提供即时验证反馈,而无需等待与服务器的往返。同时,客户端验证对于恶意方来说太容易绕过(例如,通过关闭浏览器中的 JavaScript 来绕过基于 JavaScript 的验证),因此应将其与服务器端验证结合起来。

¥However, you can't rely on client-side validation alone for security. It is a useful user experience enhancement for your users because it gives them instant validation feedback without having to wait for a round trip to the server. At the same time, client-side validation is too easy for a malicious party to bypass (for example, by turning off JavaScript in the browser to bypass JavaScript-based validation), so it should be combined with server-side validation.

任何信誉良好的服务器端框架都会提供验证表单提交的功能。此外,常见的最佳实践是转义构成可执行语法一部分的任何特殊字符,从而使任何输入的代码不再可执行并被视为纯文本。

¥Any reputable server-side framework will provide functionality for validating form submissions. In addition, a common best practice is to escape any special characters that form part of executable syntax, thereby making any entered code no longer executable and treated as plain text.

防止点击劫持

¥Protect against clickjacking

clickjacking 中,用户被欺骗点击 UI 元素,该元素执行的操作与用户期望的不同。这可能是嵌入的第三方内容固有的风险(确保你信任嵌入到你网站中的内容),并且它也可能与网络钓鱼结合在一起。

¥In clickjacking, a user is fooled into clicking on a UI element that performs an action different from what the user expects. This can be a risk inherent in embedded third-party content (make sure you trust what is being embedded into your site), and it can also be combined with phishing.

以下功能可以帮助防止点击劫持:

¥The following features can help guard against clickjacking:

HTTP X 帧选项

X-Frame-Options HTTP 响应标头可用于指示是否应允许浏览器以 <frame><iframe><embed><object> 呈现页面。网站可以利用这一点来避免 clickjacking 攻击,确保其内容不会嵌入到其他网站中。

CSP:frame-ancestors

HTTP Content-Security-Policy (CSP) frame-ancestors 指令指定可以使用 <frame><iframe><object><embed> 嵌入页面的有效父级。

也可以看看

¥See also