Skip to content

This is a demo project for the SecTester JS SDK framework, with some installation and usage examples

License

Notifications You must be signed in to change notification settings

Goumies/sectester-js-demo

 
 

Repository files navigation

SecTester SDK Demo

Table of contents

About this project

This is a demo project for the SecTester JS SDK framework, with some installation and usage examples. We recommend forking it and playing around, that’s what it’s for!

About SecTester

Bright is a developer-first Dynamic Application Security Testing (DAST) scanner.

SecTester is a new tool that integrates our enterprise-grade scan engine directly into your unit tests.

With SecTester you can:

  • Test every function and component directly
  • Run security scans at the speed of unit tests
  • Find vulnerabilities with no false positives, before you finalize your Pull Request

Trying out Bright’s SecTester is free 💸, so let’s get started!

⚠️ Disclaimer

The SecTester project is currently in beta as an early-access tool. We are looking for your feedback to make it the best possible solution for developers, aimed to be used as part of your team’s SDLC. We apologize if not everything will work smoothly from the start, and hope a few bugs or missing features will be no match for you!

Thank you! We appreciate your help and feedback!

Setup

Fork and clone this repo

  1. Press the ‘fork’ button to make a copy of this repo in your own GH account
  2. In your forked repo, clone this project down to your local machine using either SSH or HTTP

Get a Bright API key

  1. Register for a free account at Bright’s # page
  2. Optional: Skip the quickstart wizard and go directly to User API key creation
  3. Create a Bright API key (check out our doc on how to create a user key)
  4. Save the Bright API key
    1. We recommend using your Github repository secrets feature to store the key, accessible via the Settings > Security > Secrets > Actions configuration. We use the ENV variable called BRIGHT_TOKEN in our examples
    2. If you don’t use that option, make sure you save the key in a secure location. You will need to access it later on in the project but will not be able to view it again.
    3. More info on how to use ENV vars in Github actions

Explore the demo application

Navigate to your local version of this project. Then, in your command line, install the dependencies:

$ npm ci

The whole list of required variables to start the demo application is described in .env.example file. The template for this .env file is available in the root folder.

After that, you can easily create a .env file from the template by issuing the following command:

$ cp .env.example .env

Once it is done, just put your previously received API key into the BRIGHT_TOKEN variable in your .env file.

Then you have to build and run services with Docker. Start Docker, and issue the command as follows:

$ docker compose -f docker-compose.yaml up -d

To initialize DB schema, you should execute a migration, as shown here:

$ npm run migration:up

Finally, perform this command in terminal to run the application:

$ npm start

While having the application running, open a browser and type http://localhost:3000/api, and hit enter. You should see the Swagger UI page for that application that allows you to test the RESTFul CRUD API, like in the following screenshot:

Swagger UI

To explore the Swagger UI:

  • Click on the POST /users endpoint
  • Click on the "Try it out" button
  • Click on the blue "Execute" button
  • Then you should see a view similar to the following, where you can see the JSON returned from the API:

Swagger UI

Then you can start tests with SecTester against these endpoints as follows (make sure you use a new terminal window, as the original is still running the API for us!)

$ npm run test:sec

You will find tests written with SecTester in the ./test/sec folder.

This can take a few minutes, and then you should see the result, like in the following screenshot:

 FAIL  test/sec/users.e2e-spec.ts (453.752 s)
  /users
    POST /
      ✓ should not have XSS (168279 ms)
    GET /:id
      ✕ should not have SQLi (282227 ms)

  ● /users › GET /:id › should not have SQLi

    IssueFound: Target is vulnerable

    Issue in Bright UI:   https://app.neuralegion.com/scans/mKScKCEJRq2nvVkzEHUArB/issues/4rXuWAQTekbJfa9Rc7vHAX
    Name:                 SQL Injection: Blind Boolean Based
    Severity:             High
    Remediation:
    If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated. Process SQL queries using prepared statements, parameterized queries, or stored procedures. These features should accept parameters or variables and support strong typing. Do not dynamically construct and execute query strings within these features using 'exec' or similar functionality, since this may re-introduce the possibility of SQL injection
    Details:
    A SQL injection attack consists of insertion or 'injection' of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands, In a BLIND SQLi scenario there is no response data, but the application is still vulnerable via boolean-based (10=10) and other techniques.
    Extra Details:
    ● Injection Points
        Parameter: #1* (URI)
            Type: boolean-based blind
            Title: AND boolean-based blind - WHERE or HAVING clause
            Payload: http://localhost:56774/users/1 AND 2028=2028
        Database Banner: 'postgresql 14.3 on x86_64-pc-linux-musl, compiled by gcc (alpine 11.2.1_git20220219) 11.2.1 20220219, 64-bit'

    References:
    ● https://cwe.mitre.org/data/definitions/89.html
    ● https://www.owasp.org/index.php/Blind_SQL_Injection
    ● https://www.neuralegion.com/blog/blind-sql-injection/
    ● https://kb.neuralegion.com/#/guide/vulnerabilities/32-sql-injection.md

      at SecScan.assert (../packages/runner/src/lib/SecScan.ts:59:13)
          at runMicrotasks (<anonymous>)
      at SecScan.run (../packages/runner/src/lib/SecScan.ts:37:7)
      at Object.<anonymous> (sec/users.e2e-spec.ts:71:7)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        453.805 s
Ran all test suites matching /test\/sec/i.

A full configuration example

Now you will look under the hood to see how this all works. In the following example, we will test the RESTFul CRUD API for any instances of SQL injection. Jest is provided as the testing framework, that provides assert functions and test-double utilities that help with mocking, spying, etc.

To start the webserver within the same process with tests, not in a remote environment or container, we use Nest.js testing utilities. You don’t have to use Nest.js, but it is what we chose for this project. The code is as follows:

// ./test/sec/users.e2e-spec.ts
import { UsersModule } from '../../src/users';
import config from '../../src/mikro-orm.config';
import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { MikroOrmModule } from '@mikro-orm/nestjs';

describe('/users', () => {
  let app!: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [UsersModule, MikroOrmModule.forRoot(config)]
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  afterAll(() => app.close());
});

The @sectester/runner package provides a set of utilities that allows scanning the demo application for vulnerabilities. Let's expand the previous example using the built-in SecRunner class:

let runner!: SecRunner;
let app!: INestApplication;

// ...

beforeEach(async () => {
  runner = new SecRunner({ hostname: 'app.neuralegion.com' });

  await runner.init();
});

afterEach(() => runner.clear());

To set up a runner, create a SecRunner instance on the top of the file, passing a configuration as follows:

import { SecRunner } from '@sectester/runner';

const runner = new SecRunner({ hostname: 'app.neuralegion.com' });

After that, you have to initialize a SecRunner instance:

await runner.init();

The runner is now ready to perform your tests. To start scanning your endpoint, first, you have to create a SecScan instance. We do this with runner.createScan as shown in the example below.

Now, you will write and run your first unit test!

Let's verify the GET /users/:id endpoint for SQLi:

describe('GET /:id', () => {
  it('should not have SQLi', async () => {
    await runner
      .createScan({
        name: expect.getState().currentTestName,
        tests: [TestType.SQLI],
        attackParamLocations: [AttackParamLocation.PATH]
      })
      .threshold(Severity.MEDIUM)
      .timeout(timeout)
      .run({
        method: 'GET',
        url: `${baseUrl}/users/1`
      });
  });
});

This will raise an exception when the test fails, with remediation information and a deeper explanation of SQLi, right in your command line!

Let's look at another test, this time for XSS.

describe('POST /', () => {
  it('should not have XSS', async () => {
    await runner
      .createScan({
        name: expect.getState().currentTestName,
        tests: [TestType.XSS],
        attackParamLocations: [AttackParamLocation.BODY]
      })
      .threshold(Severity.MEDIUM)
      .timeout(timeout)
      .run({
        method: 'POST',
        url: `${baseUrl}/users`,
        body: { firstName: 'Test', lastName: 'Test' }
      });
  });
});

As you can see, writing a new test for XSS follows the same pattern as above. You create a scan, set a severity threshold, add a timeout, and test the endpoint using TestType.XSS.

Here is a completed test/sec/users.e2e-spec.ts file with all the tests and configuration set up.

import { UsersModule } from '../../src/users';
import config from '../../src/mikro-orm.config';
import { SecRunner } from '@sectester/runner';
import { AttackParamLocation, Severity, TestType } from '@sectester/scan';
import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigModule } from '@nestjs/config';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Server } from 'https';

describe('/users', () => {
  const timeout = 300000;
  jest.setTimeout(timeout);

  let runner!: SecRunner;
  let app!: INestApplication;
  let baseUrl!: string;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        UsersModule,
        ConfigModule.forRoot(),
        MikroOrmModule.forRoot(config)
      ]
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();

    const server = app.getHttpServer();

    server.listen(0);

    const port = server.address().port;
    const protocol = app instanceof Server ? 'https' : 'http';
    baseUrl = `${protocol}://localhost:${port}`;
  });

  afterAll(() => app.close());

  beforeEach(async () => {
    runner = new SecRunner({ hostname: process.env.BRIGHT_HOSTNAME! });

    await runner.init();
  });

  afterEach(() => runner.clear());

  describe('POST /', () => {
    it('should not have XSS', async () => {
      await runner
        .createScan({
          name: expect.getState().currentTestName,
          tests: [TestType.XSS],
          attackParamLocations: [AttackParamLocation.BODY]
        })
        .threshold(Severity.MEDIUM)
        .timeout(timeout)
        .run({
          method: 'POST',
          url: `${baseUrl}/users`,
          body: { firstName: 'Test', lastName: 'Test' }
        });
    });
  });

  describe('GET /:id', () => {
    it('should not have SQLi', async () => {
      await runner
        .createScan({
          name: expect.getState().currentTestName,
          tests: [TestType.SQLI],
          attackParamLocations: [AttackParamLocation.PATH]
        })
        .threshold(Severity.MEDIUM)
        .timeout(timeout)
        .run({
          method: 'GET',
          url: `${baseUrl}/users/1`
        });
    });
  });
});

To clarify an attack surface and speed up the test, we suggest making clear where to discover parameters according to the source code.

// ./src/users/users.service.ts
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get(':id')
  public findOne(@Param('id') id: number): Promise<User | null> {
    return this.usersService.findOne(id);
  }
}

For the example above, it should look like this:

const scan = runner.createScan({
  tests: [TestType.SQLI],
  attackParamLocations: [AttackParamLocation.PATH]
});

Finally, to run a scan against the endpoint, you have to obtain a port to which the server listens. For that, we should adjust a bit the example above:

let runner!: SecRunner;
let app!: INestApplication;
let baseUrl!: string;

beforeAll(async () => {
  // ...

  const server = app.getHttpServer();

  server.listen(0);

  const port = server.address().port;
  const protocol = app instanceof Server ? 'https' : 'http';
  baseUrl = `${protocol}://localhost:${port}`;
});

Now, you can use the baseUrl to set up a target:

await scan.run({
  method: 'GET',
  url: `${baseUrl}/users/1`
});

By default, each found issue will cause the scan to stop. To control this behavior you can set a severity threshold using the `threshold` method. Since SQLi (SQL injection) is considered to be high severity issue, we can pass Severity.HIGH for stricter checks:

scan.threshold(Severity.HIGH);

To avoid long-running test, you can specify a timeout, to say how long to wait before aborting it:

scan.timeout(300000);

To make sure that Jest won't abort tests early, you should align a test timeout with a scan timeout as follows:

jest.setTimeout(300000);

Finally, the test should look like this:

it('should not have SQLi', async () => {
  await runner
    .createScan({
      tests: [TestType.SQLI],
      attackParamLocations: [AttackParamLocation.PATH]
    })
    .threshold(Severity.MEDIUM)
    .timeout(300000)
    .run({
      method: 'GET',
      url: `${baseUrl}/users/1`
    });
});

Full documentation can be found in the @sectester/runner README.

Recommended tests

Test name Description Usage in SecTester Detectable vulnerabilities
Broken JWT Authentication Tests for secure implementation of JSON Web Token (JWT) in the application jwt - Broken JWT Authentication
Broken SAML Authentication Tests for secure implementation of SAML authentication in the application broken_saml_auth - Broken SAML Authentication
Brute Force Login Tests for availability of commonly used credentials brute_force_login - Brute Force Login
Business Constraint Bypass Tests if the limitation of number of retrievable items via an API call is configured properly business_constraint_bypass - Business Constraint Bypass
Client-Side XSS
(DOM Cross-Site Scripting)
Tests if various application DOM parameters are vulnerable to JavaScript injections dom_xss - Reflective Cross-site scripting (rXSS)

- Persistent Cross-site scripting (pXSS)
Common Files Exposure Tests if common files that should not be accessible are accessible common_files - Exposed Common File
Cookie Security Check Tests if the application uses and implements cookies with secure attributes cookie_security - Sensitive Cookie in HTTPS Session Without Secure Attribute

- Sensitive Cookie Without HttpOnly Flag

- Sensitive Cookie Weak Session ID
Cross-Site Request Forgery (CSRF) Tests application forms for vulnerable cross-site filling and submitting csrf - Unauthorized Cross-Site Request Forgery (CSRF)

- Authorized Cross-Site Request Forgery (CSRF)
Cross-Site Scripting (XSS) Tests if various application parameters are vulnerable to JavaScript injections xss - Reflective Cross-Site Scripting (rXSS)

- Persistent Cross-Site Scripting (pXSS)
Default Login Location Tests if login form location in the target application is easy to guess and accessible default_login_location - Default Login Location
Directory Listing Tests if server-side directory listing is possible directory_listing - Directory Listing
Email Header Injection Tests if it is possible to send emails to other addresses through the target application mailing server, which can lead to spam and phishing email_injection - Email Header Injection
Exposed AWS S3 Buckets Details
(Open Buckets)
Tests if exposed AWS S3 links lead to anonymous read access to the bucket open_buckets - Exposed AWS S3 Buckets Details
Exposed Database Details
(Open Database)
Tests if exposed database connection strings are open to public connections open_buckets - Exposed Database Details

- Exposed Database Connection String
Full Path Disclosure (FPD) Tests if various application parameters are vulnerable to exposure of errors that include full webroot path full_path_disclosure - Full Path Disclosure
Headers Security Check Tests for proper Security Headers configuration header_security - Misconfigured Security Headers

- Missing Security Headers

- Insecure Content Secure Policy Configuration
HTML Injection Tests if various application parameters are vulnerable to HTML injection html_injection - HTML Injection
Improper Assets Management Tests if older or development versions of API endpoints are exposed and can be used to get unauthorized access to data and privileges improper_asset_management - Improper Assets Management
Insecure HTTP Method
(HTTP Method Fuzzer)
Tests enumeration of possible HTTP methods for vulnerabilities http_method_fuzzing - Insecure HTTP Method
Insecure TLS Configuration Tests SSL/TLS ciphers and configurations for vulnerabilities insecure_tls_configuration - Insecure TLS Configuration
Known JavaScript Vulnerabilities
(JavaScript Vulnerabilities Scanning)
Tests for known JavaScript component vulnerabilities retire_js - JavaScript Component with Known Vulnerabilities
Known WordPress Vulnerabilities
(WordPress Scan)
Tests for known WordPress vulnerabilities and tries to enumerate a list of users wordpress - WordPress Component with Known Vulnerabilities
LDAP Injection Tests if various application parameters are vulnerable to unauthorized LDAP access ldapi - LDAP Injection

- LDAP Error
Local File Inclusion (LFI) Tests if various application parameters are vulnerable to loading of unauthorized local system resources lfi - Local File Inclusion (LFI)
Mass Assignment Tests if it is possible to create requests with additional parameters to gain privilege escalation mass_assignment - Mass Assignment
OS Command Injection Tests if various application parameters are vulnerable to Operation System (OS) commands injection osi - OS Command Injection
Prototype Pollution Tests if it is possible to inject properties into existing JavaScript objects proto_pollution - Prototype Pollution
Remote File Inclusion (RFI) Tests if various application parameters are vulnerable to loading of unauthorized remote system resources rfi - Remote File Inclusion (RFI)
Secret Tokens Leak Tests for exposure of secret API tokens or keys in the target application secret_tokens - Secret Tokens Leak
Server Side Template Injection (SSTI) Tests if various application parameters are vulnerable to server-side code execution ssti - Server Side Template Injection (SSTI)
Server Side Request Forgery (SSRF) Tests if various application parameters are vulnerable to internal resources access ssrf - Server Side Request Forgery (SSRF)
SQL Injection (SQLI) SQL Injection tests vulnerable parameters for SQL database access sqli - SQL Injection: Blind Boolean Based

- SQL Injection: Blind Time Based

- SQL Injection

- SQL Database Error Message in Response
Unrestricted File Upload Tests if file upload mechanisms are validated properly and denies upload of malicious content file_upload - Unrestricted File Upload
Unsafe Date Range
(Date Manipulation)
Tests if date ranges are set and validated properly date_manipulation - Unsafe Date Range
Unsafe Redirect
(Unvalidated Redirect)
Tests if various application parameters are vulnerable to injection of a malicious link which can redirect a user without validation unvalidated_redirect - Unsafe Redirect
User ID Enumeration Tests if it is possible to collect valid user ID data by interacting with the target application id_enumeration - Enumerable Integer-Based ID
Version Control System Data Leak Tests if it is possible to access Version Control System (VCS) resources version_control_systems - Version Control System Data Leak
XML External Entity Injection Tests if various XML parameters are vulnerable to XML parsing of unauthorized external entities xxe - XML External Entity Injection

Example of a CI configuration

You can integrate this library into any CI you use, for that you will need to add the BRIGHT_TOKEN ENV vars to your CI. Then add the following to your github actions configuration:

steps:
  - name: Run sec tests
    run: npm run test:sec
    env:
      POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
      POSTGRES_USER: ${{ secrets.POSTGRES_USER }}
      BRIGHT_TOKEN: ${{ secrets.BRIGHT_TOKEN }}
      BRIGHT_HOSTNAME: app.neuralegion.com

For a full list of CI configuration examples, check out the docs below.

Documentation & Help

Contributing

Please read contributing guidelines here.

License

Copyright © 2022 Bright Security.

This project is licensed under the MIT License - see the LICENSE file for details.

About

This is a demo project for the SecTester JS SDK framework, with some installation and usage examples

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 87.1%
  • JavaScript 11.4%
  • Shell 1.5%