---
# System prepended metadata

title: Lab 3 - Static Application Security Testing (SAST) II

---

# Lab 3 - Static Application Security Testing (SAST) II
Team #0:
- **Список пидорасов**

## Task 1 - Theory

1. Source code scanners scans source code as a plain text (un-compiled code) and binary scanners scans binary files (compiled code)
2. Abstract Syntax Trees (AST) is a structure that used by compilers in order to translate source code into some intermediate language (or directly into binary files) since it is a convenient way to represent structured text as a collection of simple tockens (blocks, expressions, statements etc.). It is very effective to use AST in order to find structural patterns that matches vulnerable code
3. SAST tools are used in order to scan code in order to identify vulnerabilites and secret detection tools scans code in order to find secrets. As publishing secrets is a security thread and secret detection tools are static (they do not run code) we can consider them as a SAST tools. 

## Task 2 - Gitlab SAST with Semgrep.


1. > Deploy a complete Gitlab environment with Gitlab server and Gitlab runner(s).Check back on Lab 1 DevSecOps
   - ![](https://i.imgur.com/qCXtVnC.png)
3. > Import your project into Gitlab and add a register a runner to it.
   - ![](https://i.imgur.com/qCXtVnC.png)
5. > Integrate Semgrep with Gitlab SAST in your pipeline and scan your project( to the Semgrep default rules, add Owasp top 10 rules )
   - ```yaml
      semgrep:
       needs: []
       stage: test
       image: returntocorp/semgrep


       script: semgrep ci --gitlab-sast > gl-sast-report.json
       rules:
       - if: $CI_PIPELINE_SOURCE == "web"
       - if: $CI_PIPELINE_SOURCE == "merge_request_event"
       - if: $CI_PIPELINE_SOURCE == "push"

       variables:
         SEMGREP_RULES: >- # more at semgrep.dev/r
           p/default
           p/security-audit
           p/secrets
         SEMGREP_GITLAB_JSON: "1"

       artifacts:
         when: always
         reports:
           sast: gl-sast-report.json  
     ```
     
     ![](https://i.imgur.com/7poXUob.png)

7. > Download the jobs artifacts, analyze your results and share your understandings.
   - Негры все пидорасы
   - The project contains multiple vulnerabilities found by semgrep. For example:
       - абоба
   
   > Give your understandings of:
   - > Static Analyzers
       - Ёбаные блять
   - > Static Analyzers features
       - Негры все пидорасы
   - > Post Analyzers
       - Надо их ебать


## Task 3 - Analysis with Semgrep

### Case 1
#### Where is the vulnerability in the code?
The vulnerability can be found in `resp = r.set_cookie("username","DrewDennison")` and in `resp = r.set_cookie("username","DrewDennison")`.

#### What is the vulnerability?
Insecure way of handle `set_cookie` function: `secure`, `httponly`, and `samesite` arguments not set properly. CWE-614: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute.

#### How does it affect the code?

Inproper protection of cookies increases the risk of being stolen by attacker, which make application vulnerable to unauthorized access.

#### Semgrep rule
```yaml
rules:
  - id: secure-cookie
    patterns:
      - pattern-not: r.set_cookie(..., secure=True, httponly=True, samesite='Lax', ...)
      - pattern-not: r.set_cookie(..., secure=True, httponly=True, samesite='Strict', ...)
      - pattern: r.set_cookie(...)
    message: Found flask set_cookie with insecure configuration. Secure, httponly,
      and samesite arguments didnt set correctly. Mitigate by setting
      secure=True, httponly=True, and samesite='Lax' or samesite='Strict'.
    metadata:
      cwe: CWE 614
      category: security
      owasp: A5:2021 misconfiguration
      technology:
        - flask
    languages:
      - python
    severity: WARNING
```


### Case 2
#### Where is the vulnerability in the code?
The vulnerability can be found in `decode = tokenizer.decode(token, "password", verify=False)` and in `decode= jwt.decode(token,"password")`.

#### What is the vulnerability?
Usage of hardcoded plaintext secret. CWE-522: Insufficiently Protected Credentials

#### How does it affect the code?

Anyone who has access to the code can decode jwt tokens.

#### Semgrep rule
```yaml
rules:
  - id: hardcoded-secret
    patterns:
      - pattern: jwt.decode(..., $SECRET, ...)
      - pattern: |
          "..."
    message: Hardcoded secret is used.
    metadata:
      owasp:
        - A7:2021 authentication
        - A4:2021 insecure-design
      category: security
      technology:
        - jwt
      cwe: CWE 522
    languages:
      - python
    severity: WARNING
```

#### Project:
![](https://i.imgur.com/9k4tvva.png)


#### CI job:

##### `.gitlab-ci.yml`:
```yaml
stages:
  - test

semgrep:
  needs: []
  stage: test
  image: returntocorp/semgrep


  script: semgrep ci --gitlab-sast > gl-sast-report.json
  rules:
  - if: $CI_PIPELINE_SOURCE == "web"
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  - if: $CI_PIPELINE_SOURCE == "push"

  variables:
    SEMGREP_RULES: >- # more at semgrep.dev/r
      hardcoded-secret.yaml
      secure-cookie.yaml
    SEMGREP_GITLAB_JSON: "1"

  artifacts:
    when: always
    reports:
      sast: gl-sast-report.json
```

##### Status:
![](https://i.imgur.com/wxbhk9f.png)

##### Artifacts:
`gl-sast-report.json`:

```json
{
  "$schema": "https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/master/dist/sast-report-format.json",
  "version": "14.1.2",
  "vulnerabilities": [
    {
      "category": "sast",
      "confidence": "High",
      "cve": "lib/insecurity.ts:4b68d0a42c1de76b7655454380740256741a71fc288542416559db2654949c67:javascript.jsonwebtoken.security.jwt-hardcode.hardcoded-jwt-secret",
      "id": "ab54c5fc-cb76-ba83-a69c-590b19892a6a",
      "identifiers": [
        {
          "name": "Semgrep - javascript.jsonwebtoken.secur{
  "$schema": "https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/master/dist/sast-report-format.json",
  "version": "14.1.2",
  "vulnerabilities": [
    {
      "category": "sast",
      "confidence": "High",
      "cve": "lib/insecurity.ts:4b68d0a42c1de76b7655454380740256741a71fc288542416559db2654949c67:javascript.jsonwebtoken.security.jwt-hardcode.hardcoded-jwt-secret",
      "id": "ab54c5fc-cb76-ba83-a69c-590b19892a6a",
      "identifiers": [
        {
          "name": "Semgrep - javascript.jsonwebtoken.security.jwt-hardcode.hardcoded-jwt-secret",
          "type": "semgrep_type",
          "url": "https://semgrep.dev/r/javascript.jsonwebtoken.security.jwt-hardcode.hardcoded-jwt-secret",
          "value": "javascript.jsonwebtoken.security.jwt-hardcode.hardcoded-jwt-secret"
        }
      ],
      "location": {
        "end_line": 55,
        "file": "lib/insecurity.ts",
        "start_line": 55
      },
      "message": "A hard-coded credential was detected. It is not recommended  to store credentials in source-code, as this risks secrets being leaked and used by either an internal or external malicious adversary.  It is recommended to use environment variables to  securely provide credentials or retrieve credentials from  a secure vault or HSM (Hardware Security Module).",
      "scanner": {
        "id": "semgrep",
        "name": "Semgrep",
        "vendor": {
          "name": "Semgrep"
        }
      },
      "severity": "Medium"
    },
    {
      "category": "sast",
      "confidence": "High",
      "cve": "cypress/integration/e2e/contact.spec.ts:f8bc6e061cbfee05cac827023f23d3c71cd4a8c4929bd86935ef114c189160a7:javascript.browser.security.eval-detected.eval-detected",
      "id": "1a73979a-53ba-b748-84c0-349a3abc2424",
      "identifiers": [
        {
          "name": "Semgrep - javascript.browser.security.eval-detected.eval-detected",
          "type": "semgrep_type",
          "url": "https://semgrep.dev/r/javascript.browser.security.eval-detected",
          "value": "javascript.browser.security.eval-detected.eval-detected"
        }
      ],
      "location": {
        "end_line": 258,
        "file": "cypress/integration/e2e/contact.spec.ts",
        "start_line": 258
      },
      "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.",
      "scanner": {
        "id": "semgrep",
        "name": "Semgrep",
        "vendor": {
          "name": "Semgrep"
        }
      },
      "severity": "Medium"
    },
    {
      "category": "sast",
      "confidence": "High",
      "cve": "routes/captcha.ts:4b2cb219ebf2a5a25bf9fa17e0c124870c7d4fdaed2f0bb362836b1663045015:javascript.browse... // ommited
