--- title: "Angular" section: "Network Services" sectionSlug: "network-services-pentesting" sourcePath: "src/network-services-pentesting/pentesting-web/angular.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/network-services-pentesting/pentesting-web/angular.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0" --- # Angular ## The Checklist Checklist [from here](https://lsgeurope.com/post/angular-security-checklist).[[5]](#references) * [ ] Angular is considered a client-side framework and is not expected to provide server-side protection * [ ] Sourcemap for scripts is disabled in the project configuration * [ ] Untrusted user input is always interpolated or sanitized before being used in templates * [ ] The user has no control over server-side or client-side templates * [ ] Untrusted user input is sanitized using an appropriate security context before being trusted by the application * [ ] `BypassSecurity*` methods are not used with untrusted input * [ ] Untrusted user input is not passed to Angular classes such as `ElementRef` , `Renderer2` and `Document`, or other JQuery/DOM sinks ## What is Angular Angular is a **powerful**, **open-source** front-end framework maintained by **Google**. It uses **TypeScript** to improve code readability and debugging. Angular's template sanitization reduces common client-side vulnerabilities such as **XSS**, but it does not prevent application-logic flaws such as **open redirects**. Angular can also render on the **server side**, so both client- and server-side trust boundaries require review.[[1]](#references) ## Framework architecture In order to better understand the Angular basics, let’s go through its essential concepts. A common Angular project has the following structure:[[6]](#references) ```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 ``` According to the documentation, every Angular application has at least one component, the root component (`AppComponent`) that connects a component hierarchy with the DOM. Each component defines a class that contains application data and logic, and is associated with an HTML template that defines a view to be displayed in a target environment. The `@Component()` decorator identifies the class immediately below it as a component, and provides the template and related component-specific metadata. The `AppComponent` is defined in the `app.component.ts` file. Angular NgModules declare a compilation context for a set of components that is dedicated to an application domain, a workflow, or a closely related set of capabilities. Every Angular application has a root module, conventionally named `AppModule`, which provides the bootstrap mechanism that launches the application. An application typically contains many functional modules. The `AppModule` is defined in the `app.module.ts` file. The Angular `Router` NgModule provides a service for defining navigation paths among application states and view hierarchies. `RouterModule` is configured in `app-routing.module.ts`. For data or logic that isn't associated with a specific view, and that you want to share across components, you create a service class. A service class definition is immediately preceded by the `@Injectable()` decorator. The decorator provides the metadata that allows other providers to be injected as dependencies into your class. Dependency injection (DI) lets you keep your component classes lean and efficient. They don't fetch data from the server, validate user input, or log directly to the console; they delegate such tasks to services.[[2]](#references)[[7]](#references) ## Sourcemap configuration Angular compiles TypeScript into JavaScript according to `tsconfig.json` and builds the project according to `angular.json`. The `sourceMap` option enables or disables source maps and provides separate controls for scripts, styles, vendor code, and hidden map references.[[2]](#references)[[8]](#references) ```json "sourceMap": { "scripts": true, "styles": true, "vendor": false, "hidden": false } ``` Source maps support debugging by mapping generated files back to their original sources. Public production maps can disclose otherwise hidden source and make analysis easier. If maps are unavailable, a reviewer can still inspect the compiled JavaScript for insecure patterns.[[2]](#references) The compiled Angular JavaScript is available in browser developer tools under Sources (or Debugger), commonly as `[id].main.js`. It may end with `//# sourceMappingURL=[id].main.js.map`; setting **`hidden`** to **`true`** omits that pointer but can still generate a map for private error-reporting workflows. Disabling script source maps prevents retrieval of the map, not the compiled JavaScript. Source maps can also be enabled during a build with `ng build --source-map`.[[2]](#references) ## Data binding Binding refers to the process of communication between a component and its corresponding view. It is utilized for transferring data to and from the Angular framework. Data can be passed through various means, such as through events, interpolation, properties, or through the two-way binding mechanism. Moreover, data can also be shared between related components (parent-child relation) and between two unrelated components using the Service feature.[[2]](#references)[[22]](#references) We can classify binding by data flow:[[2]](#references) * Data source to view target (includes _interpolation_, _properties_, _attributes_, _classes_ and _styles_); can be applied by using `[]` or `{{}}` in template; * View target to data source (includes _events_); can be applied by using `()` in template; * Two-Way; can be applied by using `[()]` in template. Binding can be called on properties, events, and attributes, as well as on any public member of a source directive:[[9]](#references) | TYPE | TARGET | EXAMPLES | | --------- | -------------------------------------------------------- | -------------------------------------------------------------------- | | Property | Element property, Component property, Directive property | \ | | Event | Element event, Component event, Directive event | \ ``` * To set the property of a DOM element, you can use `Renderer2.setProperty()` method and trigger an XSS attack:[[4]](#references) ```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 ``` During our research, we also examined the behavior of other `Renderer2` methods, such as `setStyle()`, `createComment()`, and `setValue()`, in relation to XSS and CSS injections. However, we were unable to find any valid attack vectors for these methods due to their functional limitations.[[4]](#references) #### jQuery jQuery is a JavaScript library that may be used alongside Angular to manipulate DOM objects. Methods that accept HTML strings can introduce XSS when passed untrusted input, so the following patterns remain relevant in Angular projects that also depend on jQuery.[[4]](#references)[[18]](#references) * The `html()` method gets the HTML contents of the first element in the set of matched elements or sets the HTML contents of every matched element. However, by design, any jQuery constructor or method that accepts an HTML string can potentially execute code. This can occur by injection of `"); }); } } //app.component.html

some text here

``` * The `jQuery.parseHTML()` method uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. ```tsx jQuery.parseHTML(data [, context ] [, keepScripts ]) ``` As mentioned before, most jQuery APIs that accept HTML strings will run scripts that are included in the HTML. The `jQuery.parseHTML()` method does not run scripts in the parsed HTML unless `keepScripts` is explicitly `true`. However, it is still possible in most environments to execute scripts indirectly; for example, via the `` attribute.[[4]](#references)[[17]](#references) ```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 interfaces According to the W3C documentation, the `window.location` and `document.location` objects are treated as aliases in modern browsers. That is why they have similar implementation of some methods and properties, which might cause an open redirect and DOM XSS with `javascript://` schema attacks as mentioned below.[[4]](#references) * `window.location.href`(and `document.location.href`) The canonical way to get the current DOM location object is using `window.location`. It can also be used to redirect the browser to a new page. As a result, having control over this object allows us to exploit an open redirect vulnerability. ```tsx //app.component.ts ... export class AppComponent { goToUrl(): void { window.location.href = "https://google.com/about" } } //app.component.html ``` The exploitation process is identical for the following scenarios. * `window.location.assign()`(and `document.location.assign()`) This method causes the window to load and display the document at the URL specified. If we have control over this method, it might be a sink for an open redirect attack. ```tsx //app.component.ts ... export class AppComponent { goToUrl(): void { window.location.assign("https://google.com/about") } } ``` * `window.location.replace()`(and `document.location.replace()`) This method replaces the current resource with the one at the provided URL. This differs from the `assign()` method is that after using `window.location.replace()`, the current page will not be saved in session History. However, it is also possible to exploit an open redirect vulnerability when we have control over this method. ```tsx //app.component.ts ... export class AppComponent { goToUrl(): void { window.location.replace("http://google.com/about") } } ``` * `window.open()` The `window.open()` method takes a URL and loads the resource it identifies into a new or existing tab or window. Having control over this method might also be an opportunity to trigger an XSS or open redirect vulnerability. ```tsx //app.component.ts ... export class AppComponent { goToUrl(): void { window.open("https://google.com/about", "_blank") } } ``` #### Angular classes * According to Angular documentation, Angular `Document` is the same as the DOM document, which means it is possible to use common vectors for the DOM document to exploit client-side vulnerabilities in the Angular. `Document.location` properties and methods might be sinks for successful open redirect attacks as shown in the example:[[4]](#references)[[19]](#references) ```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 ``` * During the research phase, we also reviewed Angular `Location` class for open redirect vulnerabilities, but no valid vectors were found. `Location` is an Angular service that applications can use to interact with a browser's current URL. This service has several methods to manipulate the given URL - `go()` , `replaceState()`, and `prepareExternalUrl()`. However, we cannot use them for redirection to the external domain. For example:[[4]](#references)[[20]](#references) ```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")); } } ``` Result: `http://localhost:4200/http://google.com/about` * The Angular `Router` class is primarily used for navigating within the same domain and does not introduce any additional vulnerabilities to the application:[[4]](#references)[[21]](#references) ```jsx //app-routing.module.ts const routes: Routes = [ { path: '', redirectTo: 'https://google.com', pathMatch: 'full' }] ``` Result: `http://localhost:4200/https:` The following methods also navigate within the domain’s scope: ```jsx const routes: Routes = [ { path: '', redirectTo: 'ROUTE', pathMatch: 'prefix' } ] this.router.navigate(['PATH']) this.router.navigateByUrl('URL') ``` ## References - [1] [Angular](https://angular.io/) - [2] [Angular Security: The Definitive Guide (Part 1)](https://lsgeurope.com/post/angular-security-the-definitive-guide-part-1) - [3] [Angular Security: The Definitive Guide (Part 2)](https://lsgeurope.com/post/angular-security-the-definitive-guide-part-2) - [4] [Angular Security: The Definitive Guide (Part 3)](https://lsgeurope.com/post/angular-security-the-definitive-guide-part-3) - [5] [Angular Security: Checklist](https://lsgeurope.com/post/angular-security-checklist) - [6] [Workspace and project file structure](https://angular.io/guide/file-structure) - [7] [Introduction to components and templates](https://angular.io/guide/architecture-components) - [8] [Source map configuration](https://angular.io/guide/workspace-config#source-map-configuration) - [9] [Binding syntax](https://angular.io/guide/binding-syntax) - [10] [Sanitization and security contexts](https://angular.io/guide/security#sanitization-and-security-contexts) - [11] [GitHub - angular/dom\_security\_schema.ts](https://github.com/angular/angular/blob/main/packages/compiler/src/schema/dom\_security\_schema.ts) - [12] [XSS in Angular and AngularJS](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/XSS%20Injection/XSS%20in%20Angular.md) - [13] [Angular Universal](https://angular.io/guide/universal) - [14] [Angular ElementRef](https://angular.io/api/core/ElementRef) - [15] [Angular Renderer2](https://angular.io/api/core/Renderer2) - [16] [Renderer2 Example: Manipulating DOM in Angular - TekTutorialsHub](https://www.tektutorialshub.com/angular/renderer2-angular/) - [17] [jQuery API Documentation](http://api.jquery.com/) - [18] [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) - [19] [Angular Document](https://angular.io/api/common/DOCUMENT) - [20] [Angular Location](https://angular.io/api/common/Location) - [21] [Angular Router](https://angular.io/api/router/Router) - [22] [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) - [23] [DOM XSS](https://book.hacktricks.wiki/en/pentesting-web/xss-cross-site-scripting/dom-xss.html)