# Angular ## The Checklist Checklist [from here](https://lsgeurope.com/post/angular-security-checklist). * [ ] Angular은 클라이언트 측 프레임워크로 간주되며 서버 측 보호를 제공할 것으로 기대되지 않습니다. * [ ] 스크립트에 대한 소스 맵이 프로젝트 구성에서 비활성화되어 있습니다. * [ ] 신뢰할 수 없는 사용자 입력은 항상 템플릿에서 사용되기 전에 보간되거나 정리됩니다. * [ ] 사용자는 서버 측 또는 클라이언트 측 템플릿에 대한 제어 권한이 없습니다. * [ ] 신뢰할 수 없는 사용자 입력은 애플리케이션에서 신뢰하기 전에 적절한 보안 컨텍스트를 사용하여 정리됩니다. * [ ] `BypassSecurity*` 메서드는 신뢰할 수 없는 입력과 함께 사용되지 않습니다. * [ ] 신뢰할 수 없는 사용자 입력은 `ElementRef`, `Renderer2`, `Document`와 같은 Angular 클래스나 다른 JQuery/DOM 싱크에 전달되지 않습니다. ## What is Angular Angular은 **강력한** 및 **오픈 소스** 프론트 엔드 프레임워크로 **Google**에서 유지 관리합니다. **TypeScript**를 사용하여 코드 가독성과 디버깅을 향상시킵니다. 강력한 보안 메커니즘을 통해 Angular는 **XSS** 및 **오픈 리다이렉트**와 같은 일반적인 클라이언트 측 취약점을 방지합니다. 서버 측에서도 사용할 수 있어 **양쪽**에서 보안 고려 사항이 중요합니다. ## Framework architecture Angular의 기본 개념을 더 잘 이해하기 위해 필수 개념을 살펴보겠습니다. 일반적인 Angular 프로젝트는 보통 다음과 같습니다: ```bash my-workspace/ ├── ... #workspace-wide configuration files ├── src │ ├── app │ │ ├── app.module.ts #defines the root module, that tells Angular how to assemble the application │ │ ├── app.component.ts #defines the logic for the application's root component │ │ ├── app.component.html #defines the HTML template associated with the root component │ │ ├── app.component.css #defines the base CSS stylesheet for the root component │ │ ├── app.component.spec.ts #defines a unit test for the root component │ │ └── app-routing.module.ts #provides routing capability for the application │ ├── lib │ │ └── src #library-specific configuration files │ ├── index.html #main HTML page, where the component will be rendered in │ └── ... #application-specific configuration files ├── angular.json #provides workspace-wide and project-specific configuration defaults └── tsconfig.json #provides the base TypeScript configuration for projects in the workspace ``` 문서에 따르면, 모든 Angular 애플리케이션은 최소한 하나의 컴포넌트, 즉 DOM과 컴포넌트 계층을 연결하는 루트 컴포넌트(`AppComponent`)를 가지고 있습니다. 각 컴포넌트는 애플리케이션 데이터와 로직을 포함하는 클래스를 정의하며, 타겟 환경에 표시될 뷰를 정의하는 HTML 템플릿과 연결됩니다. `@Component()` 데코레이터는 그 아래의 클래스를 컴포넌트로 식별하고, 템플릿 및 관련 컴포넌트 전용 메타데이터를 제공합니다. `AppComponent`는 `app.component.ts` 파일에 정의되어 있습니다. Angular NgModules는 애플리케이션 도메인, 워크플로우 또는 밀접하게 관련된 기능 세트를 위한 컴파일 컨텍스트를 선언합니다. 모든 Angular 애플리케이션은 일반적으로 `AppModule`이라고 명명된 루트 모듈을 가지고 있으며, 이는 애플리케이션을 시작하는 부트스트랩 메커니즘을 제공합니다. 애플리케이션은 일반적으로 많은 기능 모듈을 포함합니다. `AppModule`은 `app.module.ts` 파일에 정의되어 있습니다. Angular `Router` NgModule은 애플리케이션의 다양한 상태와 뷰 계층 간의 탐색 경로를 정의할 수 있는 서비스를 제공합니다. `RouterModule`은 `app-routing.module.ts` 파일에 정의되어 있습니다. 특정 뷰와 관련이 없고 컴포넌트 간에 공유하고 싶은 데이터나 로직에 대해서는 서비스 클래스를 생성합니다. 서비스 클래스 정의는 즉시 `@Injectable()` 데코레이터로 시작됩니다. 이 데코레이터는 다른 제공자가 클래스에 종속성으로 주입될 수 있도록 하는 메타데이터를 제공합니다. 의존성 주입(DI)은 컴포넌트 클래스를 간결하고 효율적으로 유지할 수 있게 해줍니다. 이들은 서버에서 데이터를 가져오거나, 사용자 입력을 검증하거나, 콘솔에 직접 로그를 남기지 않고, 이러한 작업을 서비스에 위임합니다. ## Sourcemap 구성 Angular 프레임워크는 `tsconfig.json` 옵션을 따르며 TypeScript 파일을 JavaScript 코드로 변환한 후 `angular.json` 구성으로 프로젝트를 빌드합니다. `angular.json` 파일을 살펴보면 소스맵을 활성화하거나 비활성화하는 옵션이 있음을 확인했습니다. Angular 문서에 따르면, 기본 구성은 스크립트에 대해 소스맵 파일이 활성화되어 있으며 기본적으로 숨겨져 있지 않습니다: ```json "sourceMap": { "scripts": true, "styles": true, "vendor": false, "hidden": false } ``` 일반적으로, sourcemap 파일은 생성된 파일을 원본 파일에 매핑하여 디버깅 목적으로 사용됩니다. 따라서 프로덕션 환경에서 사용하는 것은 권장되지 않습니다. sourcemaps가 활성화되면 Angular 프로젝트의 원래 상태를 복제하여 가독성을 높이고 파일 분석에 도움이 됩니다. 그러나 비활성화된 경우, 검토자는 보안 패턴을 검색하여 컴파일된 JavaScript 파일을 수동으로 분석할 수 있습니다. 또한, Angular 프로젝트의 컴파일된 JavaScript 파일은 브라우저 개발자 도구 → Sources (또는 Debugger and Sources) → \[id].main.js에서 찾을 수 있습니다. 활성화된 옵션에 따라 이 파일의 끝에 `//# sourceMappingURL=[id].main.js.map` 행이 포함될 수 있으며, **hidden** 옵션이 **true**로 설정된 경우 포함되지 않을 수 있습니다. 그럼에도 불구하고 **scripts**에 대해 sourcemap이 비활성화되면 테스트가 더 복잡해지고 파일을 얻을 수 없습니다. 또한, `ng build --source-map`와 같이 프로젝트 빌드 중에 sourcemap을 활성화할 수 있습니다. ## 데이터 바인딩 바인딩은 구성 요소와 해당 뷰 간의 통신 프로세스를 의미합니다. 이는 Angular 프레임워크와 데이터 전송에 사용됩니다. 데이터는 이벤트, 보간, 속성 또는 양방향 바인딩 메커니즘을 통해 전달될 수 있습니다. 또한, 데이터는 관련 구성 요소(부모-자식 관계) 간 및 두 개의 관련 없는 구성 요소 간에 Service 기능을 사용하여 공유될 수 있습니다. 바인딩은 데이터 흐름에 따라 분류할 수 있습니다: * 데이터 소스에서 뷰 대상까지 (포함 _interpolation_, _properties_, _attributes_, _classes_ 및 _styles_); 템플릿에서 `[]` 또는 `{{}}`를 사용하여 적용할 수 있습니다; * 뷰 대상에서 데이터 소스까지 (포함 _events_); 템플릿에서 `()`를 사용하여 적용할 수 있습니다; * 양방향; 템플릿에서 `[()]`를 사용하여 적용할 수 있습니다. 바인딩은 속성, 이벤트 및 속성뿐만 아니라 소스 지시문의 모든 공개 멤버에서 호출할 수 있습니다: | 유형 | 대상 | 예시 | | --------- | -------------------------------------------------------- | -------------------------------------------------------------------- | | 속성 | 요소 속성, 구성 요소 속성, 지시문 속성 | \ | | 이벤트 | 요소 이벤트, 구성 요소 이벤트, 지시문 이벤트 | \ ``` * DOM 요소의 속성을 설정하려면 `Renderer2.setProperty()` 메서드를 사용하고 XSS 공격을 유발할 수 있습니다: ```tsx //app.component.ts import {Component, Renderer2, ElementRef, ViewChild, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { public constructor ( private renderer2: Renderer2 ){} @ViewChild("img") img!: ElementRef; setProperty(){ this.renderer2.setProperty(this.img.nativeElement, 'innerHTML', ''); } } //app.component.html ``` 연구 중에 우리는 XSS 및 CSS 주입과 관련하여 `Renderer2`의 다른 메서드인 `setStyle()`, `createComment()`, 및 `setValue()`의 동작도 조사했습니다. 그러나 이러한 메서드의 기능적 제한으로 인해 유효한 공격 벡터를 찾을 수 없었습니다. #### jQuery jQuery는 Angular 프로젝트에서 HTML DOM 객체를 조작하는 데 도움을 줄 수 있는 빠르고 작고 기능이 풍부한 JavaScript 라이브러리입니다. 그러나 이 라이브러리의 메서드는 XSS 취약점을 달성하기 위해 악용될 수 있는 것으로 알려져 있습니다. 취약한 jQuery 메서드가 Angular 프로젝트에서 어떻게 악용될 수 있는지 논의하기 위해 이 하위 섹션을 추가했습니다. * `html()` 메서드는 일치하는 요소 집합의 첫 번째 요소의 HTML 내용을 가져오거나 모든 일치하는 요소의 HTML 내용을 설정합니다. 그러나 설계상 HTML 문자열을 수용하는 모든 jQuery 생성자 또는 메서드는 잠재적으로 코드를 실행할 수 있습니다. 이는 `"); }); } } //app.component.html

some text here

``` * `jQuery.parseHTML()` 메서드는 문자열을 DOM 노드 집합으로 변환하기 위해 기본 메서드를 사용하며, 이를 문서에 삽입할 수 있습니다. ```tsx jQuery.parseHTML(data [, context ] [, keepScripts ]) ``` 앞서 언급했듯이 HTML 문자열을 수용하는 대부분의 jQuery API는 HTML에 포함된 스크립트를 실행합니다. `jQuery.parseHTML()` 메서드는 `keepScripts`가 명시적으로 `true`가 아닌 한 파싱된 HTML에서 스크립트를 실행하지 않습니다. 그러나 대부분의 환경에서 `` 속성을 통해 간접적으로 스크립트를 실행하는 것은 여전히 가능합니다. ```tsx //app.component.ts import { Component, OnInit } from '@angular/core'; import * as $ from 'jquery'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { ngOnInit() { $("button").on("click", function() { var $palias = $("#palias"), str = "", html = $.parseHTML(str), nodeNames = []; $palias.append(html); }); } } //app.component.html

some text

``` ### Open redirects #### DOM 인터페이스 W3C 문서에 따르면, `window.location` 및 `document.location` 객체는 최신 브라우저에서 별칭으로 처리됩니다. 그렇기 때문에 이들은 일부 메서드와 속성의 유사한 구현을 가지며, 이는 아래에 언급된 `javascript://` 스키마 공격으로 인해 열린 리디렉션 및 DOM XSS를 유발할 수 있습니다. * `window.location.href`(및 `document.location.href`) 현재 DOM 위치 객체를 가져오는 표준 방법은 `window.location`을 사용하는 것입니다. 또한 이를 사용하여 브라우저를 새 페이지로 리디렉션할 수 있습니다. 결과적으로 이 객체에 대한 제어를 가지면 열린 리디렉션 취약점을 악용할 수 있습니다. ```tsx //app.component.ts ... export class AppComponent { goToUrl(): void { window.location.href = "https://google.com/about" } } //app.component.html ``` 다음 시나리오에 대한 악용 과정은 동일합니다. * `window.location.assign()`(및 `document.location.assign()`) 이 메서드는 창이 지정된 URL에서 문서를 로드하고 표시하도록 합니다. 이 메서드에 대한 제어를 가지면 열린 리디렉션 공격의 싱크가 될 수 있습니다. ```tsx //app.component.ts ... export class AppComponent { goToUrl(): void { window.location.assign("https://google.com/about") } } ``` * `window.location.replace()`(및 `document.location.replace()`) 이 메서드는 현재 리소스를 제공된 URL의 리소스로 대체합니다. `assign()` 메서드와의 차이점은 `window.location.replace()`를 사용한 후 현재 페이지가 세션 기록에 저장되지 않는다는 것입니다. 그러나 이 메서드에 대한 제어를 가질 때 열린 리디렉션 취약점을 악용할 수도 있습니다. ```tsx //app.component.ts ... export class AppComponent { goToUrl(): void { window.location.replace("http://google.com/about") } } ``` * `window.open()` `window.open()` 메서드는 URL을 가져와서 이를 새 탭이나 기존 탭 또는 창에 로드합니다. 이 메서드에 대한 제어를 가지면 XSS 또는 열린 리디렉션 취약점을 유발할 수 있는 기회가 될 수 있습니다. ```tsx //app.component.ts ... export class AppComponent { goToUrl(): void { window.open("https://google.com/about", "_blank") } } ``` #### Angular 클래스 * Angular 문서에 따르면, Angular `Document`는 DOM 문서와 동일하므로 Angular에서 클라이언트 측 취약점을 악용하기 위해 DOM 문서에 대한 일반 벡터를 사용할 수 있습니다. `Document.location` 속성과 메서드는 아래 예제와 같이 성공적인 열린 리디렉션 공격의 싱크가 될 수 있습니다: ```tsx //app.component.ts import { Component, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(@Inject(DOCUMENT) private document: Document) { } goToUrl(): void { this.document.location.href = 'https://google.com/about'; } } //app.component.html ``` * 연구 단계에서 우리는 열린 리디렉션 취약점에 대한 Angular `Location` 클래스도 검토했지만 유효한 벡터를 찾지 못했습니다. `Location`은 애플리케이션이 브라우저의 현재 URL과 상호작용하는 데 사용할 수 있는 Angular 서비스입니다. 이 서비스는 주어진 URL을 조작하는 여러 메서드 - `go()`, `replaceState()`, 및 `prepareExternalUrl()`를 가지고 있습니다. 그러나 우리는 이를 외부 도메인으로 리디렉션하는 데 사용할 수 없습니다. 예를 들어: ```tsx //app.component.ts import { Component, Inject } from '@angular/core'; import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}], }) export class AppComponent { location: Location; constructor(location: Location) { this.location = location; } goToUrl(): void { console.log(this.location.go("http://google.com/about")); } } ``` 결과: `http://localhost:4200/http://google.com/about` * Angular `Router` 클래스는 주로 동일한 도메인 내에서 탐색하는 데 사용되며 애플리케이션에 추가적인 취약점을 도입하지 않습니다: ```jsx //app-routing.module.ts const routes: Routes = [ { path: '', redirectTo: 'https://google.com', pathMatch: 'full' }] ``` 결과: `http://localhost:4200/https:` 다음 메서드도 도메인 범위 내에서 탐색합니다: ```jsx const routes: Routes = [ { path: '', redirectTo: 'ROUTE', pathMatch: 'prefix' } ] this.router.navigate(['PATH']) this.router.navigateByUrl('URL') ``` ## 참고문헌 * [Angular](https://angular.io/) * [Angular Security: The Definitive Guide (Part 1)](https://lsgeurope.com/post/angular-security-the-definitive-guide-part-1) * [Angular Security: The Definitive Guide (Part 2)](https://lsgeurope.com/post/angular-security-the-definitive-guide-part-2) * [Angular Security: The Definitive Guide (Part 3)](https://lsgeurope.com/post/angular-security-the-definitive-guide-part-3) * [Angular Security: Checklist](https://lsgeurope.com/post/angular-security-checklist) * [Workspace and project file structure](https://angular.io/guide/file-structure) * [Introduction to components and templates](https://angular.io/guide/architecture-components) * [Source map configuration](https://angular.io/guide/workspace-config#source-map-configuration) * [Binding syntax](https://angular.io/guide/binding-syntax) * [Angular Context: Easy Data-Binding for Nested Component Trees and the Router Outlet](https://medium.com/angular-in-depth/angular-context-easy-data-binding-for-nested-component-trees-and-the-router-outlet-a977efacd48) * [Sanitization and security contexts](https://angular.io/guide/security#sanitization-and-security-contexts) * [GitHub - angular/dom\_security\_schema.ts](https://github.com/angular/angular/blob/main/packages/compiler/src/schema/dom\_security\_schema.ts) * [XSS in Angular and AngularJS](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/XSS%20Injection/XSS%20in%20Angular.md) * [Angular Universal](https://angular.io/guide/universal) * [DOM XSS](https://book.hacktricks.wiki/en/pentesting-web/xss-cross-site-scripting/dom-xss.html) * [Angular ElementRef](https://angular.io/api/core/ElementRef) * [Angular Renderer2](https://angular.io/api/core/Renderer2) * [Renderer2 Example: Manipulating DOM in Angular - TekTutorialsHub](https://www.tektutorialshub.com/angular/renderer2-angular/) * [jQuery API Documentation](http://api.jquery.com/) * [How To Use jQuery With Angular (When You Absolutely Have To)](https://blog.bitsrc.io/how-to-use-jquery-with-angular-when-you-absolutely-have-to-42c8b6a37ff9) * [Angular Document](https://angular.io/api/common/DOCUMENT) * [Angular Location](https://angular.io/api/common/Location) * [Angular Router](https://angular.io/api/router/Router)