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
    • 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 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
    # NCS Final Project ## Goal of the Project Statically analyse vulnerable [Juice Shop](https://github.com/juice-shop/juice-shop) web application with semgrep. Deploy the environment and exploit critical vulnerabilities, suggest possible fixes ## Responsibilities * Daniyar Cherekbashev - Analysis and exploitation for each vulnerability * Ali Mansour - Demo * Gleb Statkevich - Difficulties and conclusion sections, help with deployment and some vulns ## Execution plan First of all, we'll clone the Juice Shop repository to perform static analysis with semgrep. ![](https://i.imgur.com/lXbsV0Y.png) ![](https://i.imgur.com/c1ey7HN.png) 84 vulnerabilities were found, 19 of which having High severity. ![](https://i.imgur.com/7yoBzIC.png) We will deploy [Docker Container](https://hub.docker.com/r/bkimminich/juice-shop) of the application with `docker pull bkimminich/juice-shop` and `docker run -d -e "NODE_ENV=unsafe" -p 3000:3000 bkimminich/juice-shop` (**!! IMPORTANT !!** to run with environment variable `NODE_ENV=unsafe` so that all potentially unsafe challenges will be unlocked and working) and observe, exploit, and provide remediation for the most critical vulnerabilities. ![](https://i.imgur.com/8GMK0Xb.png) ![](https://i.imgur.com/uv1MLqD.png) ## Observing the vulnerabilities After deploying the enivronment, we can open it at http://localhost:3000 ![](https://i.imgur.com/jBdt1Zt.png) ## 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. ![](https://i.imgur.com/Jlst8X4.png) ### Description NoSQL injection occurs when a query, most commonly delivered by an end-user, is not sanitized, allowing the attacker to include malicious input that executes an unwanted command on the database. **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` ### Exploitation Let's examine the source code of endpoint `routes/trackOrder.ts:18` ![](https://i.imgur.com/E3GMnrs.png) As we can see, user input is inserted in the NoSQL statement without any sanitization or validation. In this case we can simply bypass `'this.orderId === ${id}'` by making `id` variable escape the quote and evaluate to true, thus retrieving all orders from the database. Let's find this endpoint in the application to validate our assumption. We firstly need to create account, add shipping address and payment information with random values, then order any item. ![](https://i.imgur.com/MVwvKKl.png) Then, when we navigate to the order history at http://localhost:3000/#/order-history, we see that the request is made to the `track-order` endpoint with our order id ![](https://i.imgur.com/d5mdCjt.png) ![](https://i.imgur.com/axxyJwu.png) After using `'||1==1||` (escaping from the string with `'`, using `||` to always evaluate to true by using `1==1` condition after) as payload we retrieve all orders of all users from the database, including the one that we just ordered ![](https://i.imgur.com/h4FjyAi.png) ![](https://i.imgur.com/5LACLJO.png) ### 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, 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: ![](https://i.imgur.com/GJxSHdS.png) ## SSTI to RCE Another finding that caught our eyes is unvalidated user input that is compiled into the template, essentially leading to SSTI vulnerability ![](https://i.imgur.com/eZmGYO7.png) ### Description Server-Side Template Injection (SSTI) vulnerability is a security flaw that allows an attacker to execute arbitrary code on a web server or other applications that use server-side templates. It occurs when user-supplied input is directly embedded into template variables without proper sanitization or validation. Exploiting this vulnerability can lead to remote code execution, enabling the attacker to gain unauthorized access, modify data, or compromise the entire system. **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` ### Exploitation This is how it looks in the code, template here is the variable that was passed by user from the username field in profile edit page. ![](https://i.imgur.com/uZWsLdg.png) User profile is located at http://localhost:3000/profile We try simple template injection like `#{3+3}` (`#{}` is pug-specific payload) and see that 6 was successfully rendered on the page. ![](https://i.imgur.com/GAPJJj8.png) After searching for existing ways to exploit SSTI on Node.js, we find out that we can use `global.process.mainModule` to import `child_process` and then execute commands/spawn shell. Let's try this simple payload `#{var spawn=global.process.mainModule.require('child_process').spawn;var child=spawn('whoami');child.on('error', function(err){console.log(err);});}` to execute `whoami` command ![](https://i.imgur.com/4DuCHJe.png) It seems that it's impossible to reach RCE in this particular Docker image, as calling spawn shell comands lead to `ENOENT` error ![](https://i.imgur.com/D5dVPmA.png) However, file reading still works, for example, with `#{const fs=require('fs');fs.readFile('../../../../../../../../../../../etc/passwd','utf-8',(err,data)=>{if(err){throw err}console.log(data)});}` payload ![](https://i.imgur.com/G6hKYCC.png) Still, SSTI is one of the most critical vulnerabilities as it typically leads to RCE in any environment with the access to shell ### 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) ## 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 ![](https://i.imgur.com/q7TJCLv.png) ### Description XXE (XML External Entity) vulnerability is a type of security flaw that occurs when an XML parser processes external entities, allowing an attacker to read files from the server. Exploiting this vulnerability can lead to sensitive information disclosure, remote code execution, or denial of service. **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` ### Exploitation XML seems to be parsed from the file uploaded by user ![](https://i.imgur.com/wx98lF2.png) One of the places where the user is able to upload the files to the server is the complaint section at http://localhost:3000/#/complain. If we open file upload window we see that only `.pdf` and `.zip` are probably accepted ![](https://i.imgur.com/nKebTbY.png) However, if we open the DOM tree and locate file input section, we see that XML is mentioned in the label ![](https://i.imgur.com/IhB6gsF.png) If we open source javascript file and search for xml, we confirm that XML files are actually accepted here ![](https://i.imgur.com/uQTcdmh.png) Let's create file `test.xml` with the following content to test if XXE actually exists here ```xml= <!--?xml version="1.0" ?--> <!DOCTYPE replace [<!ENTITY example "Doe"> ]> <userInfo> <firstName>John</firstName> <lastName>&example;</lastName> </userInfo> ``` After uploading file, open `Network` tab in devtools and find request to `file-upload` endpoint, then, open `Preview` tab ![](https://i.imgur.com/QEyUnSm.png) We see that `<lastName>&example;</lastName>` got successfully rendered to `<lastName>Doe</lastName>`. Now we can try something more useful, for example, reading `/etc/passwd` file Change `test.xml` file to the following, refresh the page and upload the file again ```xml= <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo [ <!ELEMENT foo ANY> <!ENTITY xxe SYSTEM "file:///etc/passwd" >]> <foo>&xxe;</foo> ``` Now, we see contents of `/etc/passwd` file in the preview ![](https://i.imgur.com/R87ka7T.png) ### 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. ## Difficulties faced 1. Time constraints: with aforementioned amount of vulnerabilities to analyse and exploit, it was a time-consuming process to investigate them and suggest possible fixes. 2. Resource constraints: addressing high severity vulnerabilities such as nosql injections, SSTI to RCE required significant resources in time, knowledge, and skills. 3. Coordination challenge: divide the tasks in appropriate way and cooperate in the optimal way to reveal the strengths of each team members was a challenge at the beginning. 4. Technical limitations: During the work we encountered with limitations in terms of tools, environment. At the end, there were challenges with capturing sound for demo with a fine quality ## Conclusion Despite of having several challenges we reached the goal that was set in the beginning - we performed statical analyse and revealed vulnerabilities with the suggestions of how to fix them. As for the resource we analysed, 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. ## Demo https://youtu.be/JuaC8C1Aw0I ## Links https://hub.docker.com/r/bkimminich/juice-shop https://semgrep.dev/

    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