填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

安全

Security

Web 應用程式的安全涉及到很多方面。針對常見的漏洞和攻擊,比如跨站指令碼攻擊,Angular 提供了一些內建的保護措施。本章將討論這些內建保護措施,但不會涉及應用級安全,比如使用者認證(這個使用者是誰?)和授權(這個使用者能做什麼?)。

This page describes Angular's built-in protections against common web-application vulnerabilities and attacks such as cross-site scripting attacks. It doesn't cover application-level security, such as authentication (Who is this user?) and authorization (What can this user do?).

要了解更多攻防資訊,參閱開放式 Web 應用程式安全專案(OWASP)

For more information about the attacks and mitigations described below, see OWASP Guide Project.

你可以執行現場演練 / 下載範例,在 Stackblitz 中試用並下載本頁的程式碼。

You can run the現場演練 / 下載範例in Stackblitz and download the code from there.

舉報漏洞

Reporting vulnerabilities

給我們(security@angular.io)發郵件,報告 Angular 本身的漏洞。

To report vulnerabilities in Angular itself, email us at security@angular.io.

要了解關於“谷歌如何處理安全問題”的更多資訊,參閱谷歌的安全哲學

For more information about how Google handles security issues, see Google's security philosophy.

最佳實踐

Best practices

  • 及時把 Angular 包更新到最新版本。 我們會頻繁的更新 Angular 函式庫,這些更新可能會修復之前版本中發現的安全漏洞。檢視 Angular 的更新記錄,瞭解與安全有關的更新。

    Keep current with the latest Angular library releases. We regularly update the Angular libraries, and these updates may fix security defects discovered in previous versions. Check the Angular change log for security-related updates.

  • 不要修改你的 Angular 副本。 私有的、訂製版的 Angular 往往跟不上最新版本,這可能導致你忽略重要的安全修復與增強。反之,應該在社群共享你對 Angular 所做的改進並建立 Pull Request。

    Don't modify your copy of Angular. Private, customized versions of Angular tend to fall behind the current version and may not include important security fixes and enhancements. Instead, share your Angular improvements with the community and make a pull request.

  • 避免使用本文件中帶“安全風險”標記的 Angular API。 要了解更多資訊,請參閱本章的信任那些安全的值部分。

    Avoid Angular APIs marked in the documentation as “Security Risk.” For more information, see the Trusting safe values section of this page.

防範跨站指令碼(XSS)攻擊

Preventing cross-site scripting (XSS)

跨站指令碼(XSS)允許攻擊者將惡意程式碼注入到頁面中。這些程式碼可以偷取使用者資料 (特別是它們的登入資料),還可以冒充使用者執行操作。它是 Web 上最常見的攻擊方式之一。

Cross-site scripting (XSS) enables attackers to inject malicious code into web pages. Such code can then, for example, steal user data (in particular, login data) or perform actions to impersonate the user. This is one of the most common attacks on the web.

為了防範 XSS 攻擊,你必須阻止惡意程式碼進入 DOM。比如,如果某個攻擊者能騙你把 <script> 標籤插入到 DOM,就可以在你的網站上執行任何程式碼。 除了 <script>,攻擊者還可以使用很多 DOM 元素和屬性來執行程式碼,比如 <img onerror="..."><a href="javascript:...">。 如果攻擊者所控制的資料混進了 DOM,就會導致安全漏洞。

To block XSS attacks, you must prevent malicious code from entering the DOM (Document Object Model). For example, if attackers can trick you into inserting a <script> tag in the DOM, they can run arbitrary code on your website. The attack isn't limited to <script> tags—many elements and properties in the DOM allow code execution, for example, <img onerror="..."> and <a href="javascript:...">. If attacker-controlled data enters the DOM, expect security vulnerabilities.

Angular 的“跨站指令碼安全模型”

Angular’s cross-site scripting security model

為了系統性的防範 XSS 問題,Angular 預設把所有值都當做不可信任的。 當值從範本中以屬性(Property)、DOM 元素屬性(Attribte)、CSS 類別繫結或插值等途徑插入到 DOM 中的時候, Angular 將對這些值進行無害化處理(Sanitize),對不可信的值進行編碼。

To systematically block XSS bugs, Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

Angular 的範本同樣是可執行的:範本中的 HTML、Attribute 和繫結表示式(還沒有繫結到值的時候)會被當做可信任的。 這意味著應用必須防止把可能被攻擊者控制的值直接編入範本的原始碼中。永遠不要根據使用者的輸入和原始範本動態產生範本原始碼! 使用離線範本編譯器是防範這類別“範本注入”漏洞的有效途徑。

Angular templates are the same as executable code: HTML, attributes, and binding expressions (but not the values bound) in templates are trusted to be safe. This means that applications must prevent values that an attacker can control from ever making it into the source code of a template. Never generate template source code by concatenating user input and templates. To prevent these vulnerabilities, use the offline template compiler, also known as template injection.

無害化處理與安全環境

Sanitization and security contexts

無害化處理會審查不可信的值,並將它們轉換成可以安全插入到 DOM 的形式。多數情況下,這些值並不會在處理過程中發生任何變化。 無害化處理的方式取決於所在的環境:一個在 CSS 裡面無害的值,可能在 URL 裡很危險。

Sanitization is the inspection of an untrusted value, turning it into a value that's safe to insert into the DOM. In many cases, sanitization doesn't change a value at all. Sanitization depends on context: a value that's harmless in CSS is potentially dangerous in a URL.

Angular 定義了四個安全環境 - HTML,樣式,URL,和資源 URL:

Angular defines the following security contexts:

  • HTML:值需要被解釋為 HTML 時使用,比如當繫結到 innerHTML 時。

    HTML is used when interpreting a value as HTML, for example, when binding to innerHtml.

  • 樣式:值需要作為 CSS 繫結到 style 屬性時使用。

    Style is used when binding CSS into the style property.

  • URL:值需要被用作 URL 屬性時使用,比如 <a href>

    URL is used for URL properties, such as <a href>.

  • 資源 URL的值需要作為程式碼進行載入並執行,比如 <script src> 中的 URL。

    Resource URL is a URL that will be loaded and executed as code, for example, in <script src>.

Angular 會對前三項中種不可信的值進行無害化處理,但不能對第四種資源 URL 進行無害化,因為它們可能包含任何程式碼。在開發模式下, 如果在進行無害化處理時需要被迫改變一個值,Angular 就會在控制檯上輸出一個警告。

Angular sanitizes untrusted values for HTML, styles, and URLs; sanitizing resource URLs isn't possible because they contain arbitrary code. In development mode, Angular prints a console warning when it has to change a value during sanitization.

無害化範例

Sanitization example

下面的例子綁定了 htmlSnippet 的值,一次把它放進插值裡,另一次把它繫結到元素的 innerHTML 屬性上。

The following template binds the value of htmlSnippet, once by interpolating it into an element's content, and once by binding it to the innerHTML property of an element:

<h3>Binding innerHTML</h3> <p>Bound value:</p> <p class="e2e-inner-html-interpolated">{{htmlSnippet}}</p> <p>Result of binding to innerHTML:</p> <p class="e2e-inner-html-bound" [innerHTML]="htmlSnippet"></p>
src/app/inner-html-binding.component.html
      
      <h3>Binding innerHTML</h3>
<p>Bound value:</p>
<p class="e2e-inner-html-interpolated">{{htmlSnippet}}</p>
<p>Result of binding to innerHTML:</p>
<p class="e2e-inner-html-bound" [innerHTML]="htmlSnippet"></p>
    

插值的內容總會被編碼 - 其中的 HTML 不會被解釋,所以瀏覽器會在元素的文字內容中顯示尖括號。

Interpolated content is always escaped—the HTML isn't interpreted and the browser displays angle brackets in the element's text content.

如果希望這段 HTML 被正常解釋,就必須繫結到一個 HTML 屬性上,比如 innerHTML。但是如果把一個可能被攻擊者控制的值繫結到 innerHTML 就會導致 XSS 漏洞。 比如,包含在 <script> 標籤的程式碼就會被執行:

For the HTML to be interpreted, bind it to an HTML property such as innerHTML. But binding a value that an attacker might control into innerHTML normally causes an XSS vulnerability. For example, code contained in a <script> tag is executed:

export class InnerHtmlBindingComponent { // For example, a user/attacker-controlled value from a URL. htmlSnippet = 'Template <script>alert("0wned")</script> <b>Syntax</b>'; }
src/app/inner-html-binding.component.ts (class)
      
      export class InnerHtmlBindingComponent {
  // For example, a user/attacker-controlled value from a URL.
  htmlSnippet = 'Template <script>alert("0wned")</script> <b>Syntax</b>';
}
    

Angular 認為這些值是不安全的,並自動進行無害化處理。它會移除 <script> 標籤,但保留安全的內容,比如該片段中的 <b> 元素。

Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element.

避免直接使用 DOM API

Direct use of the DOM APIs and explicit sanitization calls

瀏覽器內建的 DOM API 不會自動保護你免受安全漏洞的侵害。比如 document、透過 ElementRef 拿到的節點和很多第三方 API,都可能包含不安全的方法。如果你使用能操縱 DOM 的其它函式庫,也同樣無法藉助像 Angular 插值那樣的自動清理功能。 所以,要避免直接和 DOM 打交道,而是儘可能使用 Angular 範本。

The built-in browser DOM APIs don't automatically protect you from security vulnerabilities. For example, document, the node available through ElementRef, and many third-party APIs contain unsafe methods. In the same way, if you interact with other libraries that manipulate the DOM, you likely won't have the same automatic sanitization as with Angular interpolations. Avoid directly interacting with the DOM and instead use Angular templates where possible.

瀏覽器內建的 DOM API 不會自動針對安全漏洞進行防護。比如,document(它可以透過 ElementRef 訪問)以及其它第三方 API 都可能包含不安全的方法。 要避免直接與 DOM 互動,只要可能,就儘量使用 Angular 範本。

For cases where this is unavoidable, use the built-in Angular sanitization functions. Sanitize untrusted values with the DomSanitizer.sanitize method and the appropriate SecurityContext. That function also accepts values that were marked as trusted using the bypassSecurityTrust... functions, and will not sanitize them, as described below.

內容安全策略

Content security policy

內容安全策略(CSP)是用來防範 XSS 的縱深防禦技術。 要開啟 CSP,請配置你的 Web 伺服器,讓它返回合適的 HTTP 頭 Content_Security_Policy。 要了解關於內容安全策略的更多資訊,請參閱 HTML5Rocks 上的內容安全策略簡介

Content Security Policy (CSP) is a defense-in-depth technique to prevent XSS. To enable CSP, configure your web server to return an appropriate Content-Security-Policy HTTP header. Read more about content security policy at the Web Fundamentals guide on the Google Developers website.

使用離線範本編譯器

Use the offline template compiler

離線範本編譯器阻止了一整套被稱為“範本注入”的漏洞,並能顯著增強應用程式的效能。儘量在產品發佈時使用離線範本編譯器, 而不要動態產生範本(比如在程式碼中拼接字串產生範本)。由於 Angular 會信任範本本身的程式碼,所以,動態產生的範本 —— 特別是包含使用者資料的範本 —— 會繞過 Angular 自帶的保護機制。 要了解如何用安全的方式動態建立表單,請參閱動態表單一章。

The offline template compiler prevents a whole class of vulnerabilities called template injection, and greatly improves application performance. Use the offline template compiler in production deployments; don't dynamically generate templates. Angular trusts template code, so generating templates, in particular templates containing user data, circumvents Angular's built-in protections. For information about dynamically constructing forms in a safe way, see the Dynamic Forms guide page.

伺服器端 XSS 保護

Server-side XSS protection

伺服器端構造的 HTML 很容易受到注入攻擊。當需要在伺服器端產生 HTML 時(比如 Angular 應用的初始頁面), 務必使用一個能夠自動進行無害化處理以防範 XSS 漏洞的後端範本語言。不要在伺服器端使用範本語言產生 Angular 範本, 這樣會帶來很高的“範本注入”風險。

HTML constructed on the server is vulnerable to injection attacks. Injecting template code into an Angular application is the same as injecting executable code into the application: it gives the attacker full control over the application. To prevent this, use a templating language that automatically escapes values to prevent XSS vulnerabilities on the server. Don't generate Angular templates on the server side using a templating language; doing this carries a high risk of introducing template-injection vulnerabilities.

信任安全值

Trusting safe values

有時候,應用程式確實需要包含可執行的程式碼,比如使用 URL 顯示 <iframe>,或者構造出有潛在危險的 URL。 為了防止在這種情況下被自動無害化,你可以告訴 Angular:我已經審查了這個值,檢查了它是怎麼產生的,並確信它總是安全的。 但是千萬要小心!如果你信任了一個可能是惡意的值,就會在應用中引入一個安全漏洞。如果你有疑問,請找一個安全專家複查下。

Sometimes applications genuinely need to include executable code, display an <iframe> from some URL, or construct potentially dangerous URLs. To prevent automatic sanitization in any of these situations, you can tell Angular that you inspected a value, checked how it was generated, and made sure it will always be secure. But be careful. If you trust a value that might be malicious, you are introducing a security vulnerability into your application. If in doubt, find a professional security reviewer.

注入 DomSanitizer 服務,然後呼叫下面的方法之一,你就可以把一個值標記為可信任的。

To mark a value as trusted, inject DomSanitizer and call one of the following methods:

  • bypassSecurityTrustHtml

  • bypassSecurityTrustScript

  • bypassSecurityTrustStyle

  • bypassSecurityTrustUrl

  • bypassSecurityTrustResourceUrl

記住,一個值是否安全取決於它所在的環境,所以你要為這個值按預定的用法選擇正確的環境。假設下面的範本需要把 javascript.alert(...) 方法繫結到 URL。

Remember, whether a value is safe depends on context, so choose the right context for your intended use of the value. Imagine that the following template needs to bind a URL to a javascript:alert(...) call:

<h4>An untrusted URL:</h4> <p><a class="e2e-dangerous-url" [href]="dangerousUrl">Click me</a></p> <h4>A trusted URL:</h4> <p><a class="e2e-trusted-url" [href]="trustedUrl">Click me</a></p>
src/app/bypass-security.component.html (URL)
      
      <h4>An untrusted URL:</h4>
<p><a class="e2e-dangerous-url" [href]="dangerousUrl">Click me</a></p>
<h4>A trusted URL:</h4>
<p><a class="e2e-trusted-url" [href]="trustedUrl">Click me</a></p>
    

通常,Angular 會自動無害化這個 URL 並禁止危險的程式碼。為了防止這種行為,可以呼叫 bypassSecurityTrustUrl 把這個 URL 值標記為一個可信任的 URL:

Normally, Angular automatically sanitizes the URL, disables the dangerous code, and in development mode, logs this action to the console. To prevent this, mark the URL value as a trusted URL using the bypassSecurityTrustUrl call:

constructor(private sanitizer: DomSanitizer) { // javascript: URLs are dangerous if attacker controlled. // Angular sanitizes them in data binding, but you can // explicitly tell Angular to trust this value: this.dangerousUrl = 'javascript:alert("Hi there")'; this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
src/app/bypass-security.component.ts (trust-url)
      
      constructor(private sanitizer: DomSanitizer) {
  // javascript: URLs are dangerous if attacker controlled.
  // Angular sanitizes them in data binding, but you can
  // explicitly tell Angular to trust this value:
  this.dangerousUrl = 'javascript:alert("Hi there")';
  this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
    

如果需要把使用者輸入轉換為一個可信任的值,可以在控制器方法中處理。下面的範本允許使用者輸入一個 YouTube 視訊的 ID, 然後把相應的視訊載入到 <iframe> 中。<iframe src> 是一個“資源 URL”的安全環境,因為不可信的原始碼可能作為檔案下載到本地,被毫無防備的使用者執行。 所以要呼叫一個控制器方法來構造一個新的、可信任的視訊 URL,這樣 Angular 就會允許把它繫結到 <iframe src>

If you need to convert user input into a trusted value, use a controller method. The following template allows users to enter a YouTube video ID and load the corresponding video in an <iframe>. The <iframe src> attribute is a resource URL security context, because an untrusted source can, for example, smuggle in file downloads that unsuspecting users could execute. So call a method on the controller to construct a trusted video URL, which causes Angular to allow binding into <iframe src>:

<h4>Resource URL:</h4> <p>Showing: {{dangerousVideoUrl}}</p> <p>Trusted:</p> <iframe class="e2e-iframe-trusted-src" width="640" height="390" [src]="videoUrl"></iframe> <p>Untrusted:</p> <iframe class="e2e-iframe-untrusted-src" width="640" height="390" [src]="dangerousVideoUrl"></iframe>
src/app/bypass-security.component.html (iframe)
      
      <h4>Resource URL:</h4>
<p>Showing: {{dangerousVideoUrl}}</p>
<p>Trusted:</p>
<iframe class="e2e-iframe-trusted-src" width="640" height="390" [src]="videoUrl"></iframe>
<p>Untrusted:</p>
<iframe class="e2e-iframe-untrusted-src" width="640" height="390" [src]="dangerousVideoUrl"></iframe>
    
updateVideoUrl(id: string) { // Appending an ID to a YouTube URL is safe. // Always make sure to construct SafeValue objects as // close as possible to the input data so // that it's easier to check if the value is safe. this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id; this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl); }
src/app/bypass-security.component.ts (trust-video-url)
      
      updateVideoUrl(id: string) {
  // Appending an ID to a YouTube URL is safe.
  // Always make sure to construct SafeValue objects as
  // close as possible to the input data so
  // that it's easier to check if the value is safe.
  this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id;
  this.videoUrl =
      this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl);
}
    

HTTP 級別的漏洞

HTTP-level vulnerabilities

Angular 內建了一些支援來防範兩個常見的 HTTP 漏洞:跨站請求偽造(XSRF)和跨站指令碼包含(XSSI)。 這兩個漏洞主要在伺服器端防範,但是 Angular 也自帶了一些輔助特性,可以讓客戶端的整合變得更容易。

Angular has built-in support to help prevent two common HTTP vulnerabilities, cross-site request forgery (CSRF or XSRF) and cross-site script inclusion (XSSI). Both of these must be mitigated primarily on the server side, but Angular provides helpers to make integration on the client side easier.

跨站請求偽造(XSRF)

Cross-site request forgery

在跨站請求偽造(XSRF 或 CSFR)中,攻擊者欺騙使用者,讓他們訪問一個假冒頁面(例如 evil.com), 該頁面帶有惡意程式碼,祕密的向你的應用程式伺服器傳送惡意請求(例如 example-bank.com)。

In a cross-site request forgery (CSRF or XSRF), an attacker tricks the user into visiting a different web page (such as evil.com) with malignant code that secretly sends a malicious request to the application's web server (such as example-bank.com).

假設使用者已經在 example-bank.com 登入。使用者開啟一個郵件,點選裡面的連結,在新頁面中開啟 evil.com

Assume the user is logged into the application at example-bank.com. The user opens an email and clicks a link to evil.com, which opens in a new tab.

evil.com 頁面立刻傳送惡意請求到 example-bank.com。這個請求可能是從使用者賬戶轉賬到攻擊者的賬戶。 與該請求一起,瀏覽器自動發出 example-bank.com 的 cookie。

The evil.com page immediately sends a malicious request to example-bank.com. Perhaps it's a request to transfer money from the user's account to the attacker's account. The browser automatically sends the example-bank.com cookies (including the authentication cookie) with this request.

如果 example-bank.com 伺服器缺乏 XSRF 保護,就無法辨識請求是從應用程式發來的合法請求還是從 evil.com 來的假請求。

If the example-bank.com server lacks XSRF protection, it can't tell the difference between a legitimate request from the application and the forged request from evil.com.

為了防止這種情況,你必須確保每個使用者的請求都是從你自己的應用中發出的,而不是從另一個網站發出的。 客戶端和伺服器必須合作來抵擋這種攻擊。

To prevent this, the application must ensure that a user request originates from the real application, not from a different site. The server and client must cooperate to thwart this attack.

常見的反 XSRF 技術是伺服器隨機產生一個使用者認證令牌到 cookie 中。 客戶端程式碼獲取這個 cookie,並用它為接下來所有的請求新增自訂請求頁首。 伺服器比較收到的 cookie 值與請求頁首的值,如果它們不匹配,便拒絕請求。

In a common anti-XSRF technique, the application server sends a randomly generated authentication token in a cookie. The client code reads the cookie and adds a custom request header with the token in all subsequent requests. The server compares the received cookie value to the request header value and rejects the request if the values are missing or don't match.

這個技術之所以有效,是因為所有瀏覽器都實現了同源策略。只有設定 cookie 的網站的程式碼可以訪問該站的 cookie,並為該站的請求設定自訂頁首。 這就是說,只有你的應用程式可以獲取這個 cookie 令牌和設定自訂頁首。evil.com 的惡意程式碼不能。

This technique is effective because all browsers implement the same origin policy. Only code from the website on which cookies are set can read the cookies from that site and set custom headers on requests to that site. That means only your application can read this cookie token and set the custom header. The malicious code on evil.com can't.

Angular 的 HttpClient 對這項技術的客戶端部分提供了內建的支援要了解更多資訊,參閱 HttpClient 部分

Angular's HttpClient has built-in support for the client-side half of this technique. Read about it more in the HttpClient guide.

可到 "開放式 Web 應用程式安全專案 (OWASP) " 深入瞭解 CSRF,參閱Cross-Site Request Forgery (CSRF)Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet。 這個斯坦福大學論文 Robust Defenses for Cross-Site Request Forgery 有詳盡的細節。

For information about CSRF at the Open Web Application Security Project (OWASP), see Cross-Site Request Forgery (CSRF) and Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet. The Stanford University paper Robust Defenses for Cross-Site Request Forgery is a rich source of detail.

參閱 Dave Smith 在AngularConnect 2016 關於 XSRF 的演講

See also Dave Smith's easy-to-understand talk on XSRF at AngularConnect 2016.

跨站指令碼包含(XSSI)

Cross-site script inclusion (XSSI)

跨站指令碼包含,也被稱為 Json 漏洞,它可以允許一個攻擊者的網站從 JSON API 讀取資料。這種攻擊發生在老的瀏覽器上, 它重寫原生 JavaScript 物件的建構函式,然後使用 <script> 標籤包含一個 API 的 URL。

Cross-site script inclusion, also known as JSON vulnerability, can allow an attacker's website to read data from a JSON API. The attack works on older browsers by overriding native JavaScript object constructors, and then including an API URL using a <script> tag.

只有在返回的 JSON 能像 JavaScript 一樣可以被執行時,這種攻擊才會生效。所以伺服器端會約定給所有 JSON 回應內文加上字首 ")]}',\n",來把它們標記為不可執行的, 以防範這種攻擊。

This attack is only successful if the returned JSON is executable as JavaScript. Servers can prevent an attack by prefixing all JSON responses to make them non-executable, by convention, using the well-known string ")]}',\n".

Angular 的 HttpClient 函式庫會識別這種約定,並在進一步解析之前,自動把字串 ")]}',\n" 從所有響應中去掉。

Angular's HttpClient library recognizes this convention and automatically strips the string ")]}',\n" from all responses before further parsing.

要學習更多這方面的知識,請參閱谷歌 Web 安全部落格文章的 XSSI 小節。

For more information, see the XSSI section of this Google web security blog post.

審計 Angular 應用程式

Auditing Angular applications

Angular 應用應該遵循和常規 Web 應用一樣的安全原則並按照這些原則進行審計。Angular 中某些應該在安全評審中被審計的 API( 比如bypassSecurityTrust API)都在文件中被明確標記為安全性敏感的。

Angular applications must follow the same security principles as regular web applications, and must be audited as such. Angular-specific APIs that should be audited in a security review, such as the bypassSecurityTrust methods, are marked in the documentation as security sensitive.