kiese
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Secure System Development Lab 2 - Static Application Security Testing **Team Members:** * Daniyar Cherekbashev (d.cherekbashev@innopolis.university) * Gleb Statkevich (g.statkevich@innopolis.university) * Daria Kalashnikova (d.kalashnikova@innopolis.university) ## Task 1 **1. Q: What is the differences between source code scanners and binaries scanners?** A: Source code scanners look for insecure coding practices (such as improper input validation, buffer overflows, and insecure data storage). Source code scanners are typically used during the development phase. Binary scanners look for vulnerabilities that may exist in the compiled code (buffer overflows, hardcoded credentials, and insecure permissions). Binary scanners are typically used in post-deployment security testing to identify potential vulnerabilities in a application. Both types of scanners play a crucial role in securing software applications. **2. Q: Explain how Abstract Syntax Trees (AST) can help to find vulnerabilities and what kind of vulnerabilities can be found more effective.** A: Abstract Syntax Trees (AST) are a hierarchical (tree) representation of the source code of a program, it allows use in-depth and structured analysis of the codebase. - Injection vulnerabilities: AST can be used to detect insecure input handling (ex: SQL injection) - Code injection vulnerabilities: AST can help detect vulnerabilities that come from dynamically executing code (ex: `eval()`) - Information leakage vulnerabilities: AST can help detect potential data leakage vulnerabilities, (ex: logging sensitive information, exposing sensitive data in error messages) **3. Q: What is Static Code Analysis?** A: Set of techniques of source code analysis. Its purpose is to find errors, basic mistakes, logical flaws that may lead to runtime errors or vulnerabilities. The analysis is called "static" because the source code of the software does not need to be actually executed. **4. Q: Give and explain the benefit(s) of Static Analysis Tool.** A: - Easy to integrate the analysis into pipeline and run it frequently + Increased productivity (Static analysis tools can automate the process of code review) - Early detection of essential vulnerabilities (insecure usage of functions, injections, etc.) - Increase code quality and disciple the devs to write good code **5. Q: Give and explain the limitation(s) of Static Analyzers.** A: - Only basic vulnerabilities may be detected - injections, insecure functions, improper function usage - Langugage specific - it's needed to adapt tools to any new language used - False-positivies on code which may be unable to exploit or the flaw is mitigated and False-negative (miss actual issues in the codebase) - Limited scope: code analysis based on predefined rules and patterns, which means they may not catch all types of issues or vulnerabilities and unable to analyse archtictural issues with (authentication, data flow, etc.) For this lab, we'll be using Semgrep + OWASP Juice Shop. ## Task 3.1 Semgrep - Set up your environment Imported Juice Shop project: ![image](https://hackmd.io/_uploads/rJU_fx1xR.png) Semgrep pipeline (with included owasp-top-10 rule from semgrep.dev): ```yaml= semgrep: image: semgrep/semgrep script: semgrep ci rules: - if: $CI_PIPELINE_SOURCE == "web" - if: $CI_MERGE_REQUEST_IID - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH variables: SEMGREP_APP_TOKEN: $SEMGREP_APP_TOKEN ``` After adding the pipeline, we can see that scanning is in progress in our dashboard: ![image](https://hackmd.io/_uploads/SJuE3x1gR.png) Our CI job has successfully passed and reported 81 findings. ![image](https://hackmd.io/_uploads/Byf46lJe0.png) We can now access semgrep results in the dashboard. 19 of 81 findings have high severity ![image](https://hackmd.io/_uploads/SkPO6e1eR.png) Given the high number of vulnerabilities, especially those with high severity, it is clear that the Juice Shop web application has significant security flaws. The presence of NoSQL injections, SSTI to RCE, and XXE vulnerabilities highlights the need for thorough and comprehensive security testing and remediation. ## Task 3.2 Semgrep - Analysis **Case 2:** ```python= import jwt as tokenizer # JWT Auth bypass def accept_request(): decode = tokenizer.decode(token, "password", verify=False) # JWT algorithm bypass def accept_another_request(): decode= jwt.decode(token,"password") ``` scan results ![image](https://hackmd.io/_uploads/r1IkiGyeA.png) 1. Vulnerabilities: a secret is hard-coded in the application. 2. Semgrep rules: `python.pyjwt.python-pyjwt-hardcoded-secret.python-pyjwt-hardcoded-secret` **Case 3** ```python= import sqlite3 from passlib.hash import pbkdf2_sha256 def db_init(): users = [ ('ace', pbkdf2_sha256.encrypt('123456')), ('semper', pbkdf2_sha256.encrypt('Password')), ('alex', pbkdf2_sha256.encrypt('Waiver2')) ] conn = sqlite3.connect('users.sqlite') c = conn.cursor() c.execute("DROP TABLE users") c.execute("CREATE TABLE users (user text, password text, failures int)") for u,p in users: c.execute("INSERT INTO users (user, password, failures) \ VALUES ('%s', '%s', '%d')" %(u, p, 0)) conn.commit() conn.close() if __name__ == '__main__': db_init()**** ``` scan results: ![image](https://hackmd.io/_uploads/BJxbLGJeA.png) 1. Vulnerability: execution of raw/formatted SQL query in code. 2. Semgrep rules: - `python.sqlalchemy.security.sqlalchemy-execute-raw-query.sqlalchemy-execute-raw-query` - `python.lang.security.audit.formatted-sql-query.formatted-sql-query` ### Adding Semgrep rules to CI 1. Imported cases in Gitlab: ![image](https://hackmd.io/_uploads/HkaZlKgeC.png) 2. After adding our rules in rule policies, we run our semgrep CI job in created project ![image](https://hackmd.io/_uploads/SJAMwFglR.png) As we can see, semgrep successfully detected those rule violations ![image](https://hackmd.io/_uploads/S1ciSFxeC.png) ## Task 3.3 Semgrep - Remediation We'll solve 3 issues from the OWASP Juice Shop project ### NoSQL Injection The very first vulnerability with High severity that semgrep shows to us is a potential NoSQL vulnerability that might be possible at 8 endpoints. ![image](https://hackmd.io/_uploads/H1Y0DYxlC.png) **CWE-943**: Improper Neutralization of Special Elements in Data Query Logic **CVSS v3.1** score: 4.3 `CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N/E:F/RC:C` **Remediation** To prevent NoSQL injection, it is important to validate and sanitize user input: use strict data types, filter out malicious input by using pattern matching. Also, it is important to use parameterized queries instead of dynamically constructing queries, as they were designed to specifically remove any user-interaction and separate query logic from the user input, automatically handling the proper escaping. For this case (`routes/trackOrder.ts` endpoint), for a user-defined variable `id`, we can convert it to ```javascript= const id = String(id).replace(/[^\w-]+/g, '') ``` which removes all non-alphanumeric characters from the string, making it impossible to perform injection. Example: ![image](https://hackmd.io/_uploads/HJujwk1xA.png) ### XXE Another interesting finding is the call to `parseXml()` function with the unsanitized data passed by user. This might open a potential vector of XXE attack ![image](https://hackmd.io/_uploads/rkqz9bJeR.png) **CWE-611**: Improper Restriction of XML External Entity Reference **CVSS v3.1** score: 7.5 `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N` **Remediation** Most XXE vulnerabilities arise because the application's XML parsing library supports potentially dangerous XML features that the application does not need or intend to use. The easiest and most effective way to prevent XXE attacks is to disable those features. In this case, it is enough to simply parse XML document in vm and set `noent` parameter to `false`: ```javascript= const xmlDoc = vm.runInContext('libxml.parseXml(data, { noblanks: true, noent: false, nocdata: true })', sandbox, { timeout: 2000 }) ``` `NOENT` set to `true` means that no entity nodes should be created in the parsed document, meaning that every entity is expanded. By setting it to `false` XXE attacks are not possible in any way. ### SSTI to RCE Another finding that caught our eyes is unvalidated user input that is compiled into the template, essentially leading to SSTI vulnerability ![image](https://hackmd.io/_uploads/SyXKc-JgA.png) **CWE-1336**: Improper Neutralization of Special Elements Used in a Template Engine **CVSS v3.1** score: 9.8 `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H` **Remediation** Just like in NoSQL injection, it is important to firstly sanitize user input before using it in the template. To do this, various means are possible (use of regex, white lists of authorised expressions, etc). Additionally, it is crucial to use a secure template engine that restricts execution of arbitrary code and limits the functionality of templates. For even more secure approach, run user-supplied data in a closed environment, where risky modules and features are disabled. For our specific case (pug engine), it will be enough to match user input with the regex like this `/#{(.*)}/` and, if match occurs, disallow render or remove special characters from input to render the secure version of input ![](https://i.imgur.com/W4w5EFo.png) ### Re-scanning the project After fixing all aforementioned vulnerabilities, we'll scan the project again. Latest scan showed roughly 3 findings less than it was before: ![image](https://hackmd.io/_uploads/HynoiFgeA.png) Conviniently enough, semgrep provides a `Fixed` status where we can see all vulnerabilities that were fixed within the latest commit. ![image](https://hackmd.io/_uploads/ByqXhtlx0.png) Overall, SAST with semgrep makes the progress of tracking and fixing vulnerabilities much more intuitive and easier.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully