diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/README.md b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/README.md new file mode 100644 index 0000000..a3670c8 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/README.md @@ -0,0 +1,92 @@ +# JavaScript-Semgrep-Nodejs + + + +## Getting started + +To make it easy for you to get started with GitLab, here's a list of recommended next steps. + +Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! + +## Add your files + +- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files +- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: + +``` +cd existing_repo +git remote add origin https://gitlab.aws.dev/sanjuera/javascript-semgrep-nodejs.git +git branch -M main +git push -uf origin main +``` + +## Integrate with your tools + +- [ ] [Set up project integrations](https://gitlab.aws.dev/sanjuera/javascript-semgrep-nodejs/-/settings/integrations) + +## Collaborate with your team + +- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) +- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) +- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) +- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) +- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) + +## Test and Deploy + +Use the built-in continuous integration in GitLab. + +- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) +- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) +- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) +- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) +- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) + +*** + +# Editing this README + +When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. + +## Suggestions for a good README +Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. + +## Name +Choose a self-explaining name for your project. + +## Description +Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. + +## Badges +On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. + +## Visuals +Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. + +## Installation +Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. + +## Usage +Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. + +## Support +Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. + +## Roadmap +If you have ideas for releases in the future, it is a good idea to list them in the README. + +## Contributing +State if you are open to contributions and what your requirements are for accepting them. + +For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. + +You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. + +## Authors and acknowledgment +Show your appreciation to those who have contributed to the project. + +## License +For open source projects, say how it is licensed. + +## Project status +If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/.gitkeep b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/archive_path_overwrite.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/archive_path_overwrite.ts new file mode 100644 index 0000000..8e7c5fb --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/archive_path_overwrite.ts @@ -0,0 +1,99 @@ +//Ref: https://snyk.io/research/zip-slip-vulnerability +import fs from 'fs'; +import unzip from 'unzip'; + +// {fact rule=path-traversal@v1.0 defects=1} +fs.createReadStream('archive.zip') + .pipe(unzip.Parse()) + .on('entry', (entry: { path: any; pipe: (arg0: any) => void; }) => { + const fileName = entry.path; + // Arbitrary file overwrite + // ruleid:zip_path_overwrite + entry.pipe(fs.createWriteStream(fileName)); + }); +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} +fs.createReadStream('archive.zip') + .pipe(unzip.Parse()) + .on('entry', (entry: { path: any; pipe: (arg0: any) => void; }) => { + const fileName = entry.path; + // Arbitrary file overwrite + // ruleid:zip_path_overwrite + entry.pipe(fs.writeFileSync(fileName)); + }); +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} +fs.readFile('path/to/archive.zip', function (err: any, zipContents: any) { + unzip.Parse(zipContents).on('entry', function (entry: { path: string; contents: any; }) { + var fileName = 'output/path/' + entry.path; + // Arbitrary file overwrite + // ruleid:zip_path_overwrite2 + fs.writeFileSync(fileName, entry.contents); + }); +}); +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} +//admzip +import fs from 'fs'; +var AdmZip = require('adm-zip'); +var zip = new AdmZip("archive.zip"); +var zipEntries = zip.getEntries(); +// ruleid:admzip_path_overwrite +zipEntries.forEach(function (zipEntry: { entryName: any; }) { + fs.createWriteStream(zipEntry.entryName); +}); +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} +// ruleid:admzip_path_overwrite +zip.getEntries().forEach(function (zipEntry: { entryName: any; }) { + fs.writeFileSync(zipEntry.entryName); +}); +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} +// tar-stream overwrite +import tar from 'tar-stream'; +const extract = tar.extract(); +// {fact rule=path-traversal@v1.0 defects=1} +extract.on('entry', (header: { name: any; }, stream: { pipe: (arg0: any) => void; on: (arg0: string, arg1: () => void) => void; resume: () => void; }, next: () => void) => { + // ruleid:tar_path_overwrite + const out = fs.createWriteStream(header.name); + stream.pipe(out); + stream.on('end', () => { + next(); + }) + stream.resume(); +}) +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} +tar.extract().on('entry', (header: { name: any; }, stream: { pipe: (arg0: any) => void; on: (arg0: string, arg1: () => void) => void; resume: () => void; }, next: () => void) => { + // ruleid:tar_path_overwrite + const out = fs.writeFileSync(header.name); + stream.pipe(out); + stream.on('end', () => { + next(); + }) + stream.resume(); +}) +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} +///unzipper lib +fs.createReadStream('./bad.tar').pipe(extract); +import fs from 'fs'; +import unzipper from 'unzipper'; + +fs.createReadStream('path/to/archive.zip') + .pipe(unzipper.Parse()) + .on('entry', function (entry: { path: any; pipe: (arg0: any) => void; }) { + var fileName = entry.path; + // ruleid:zip_path_overwrite + entry.pipe(fs.createWriteStream(fileName)); + }); +// {/fact} + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/archive_path_overwrite.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/archive_path_overwrite.yaml new file mode 100644 index 0000000..a8aa978 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/archive_path_overwrite.yaml @@ -0,0 +1,158 @@ +rules: + - id: zip_path_overwrite + patterns: + - pattern-either: + - pattern-inside: | + $X = require('unzip'); + ... + - pattern-inside: | + $X = require('unzipper'); + ... + - pattern-inside: | + $Y.pipe($UNZIP.Parse(...)).on('entry', function $FUNC(...) { + ... + }, ...); + - pattern-not: | + $X = $FILENAME.indexOf(...); + - pattern-not: > + $FUNC.pipe($FS.createWriteStream($PATH.join(..., + $PATH.basename($FILENAME, ...)))); + - pattern-not: > + $FUNC.pipe($FS.writeFile($PATH.join(..., $PATH.basename($FILENAME, + ...)))); + - pattern-not: > + $FUNC.pipe($FS.writeFileSync($PATH.join(..., $PATH.basename($FILENAME, + ...)))); + - pattern-either: + - pattern: | + $FUNC.pipe($FS.createWriteStream($FIL, ...)); + - pattern: | + $FUNC.pipe($FS.writeFile($FIL, ...)); + - pattern: | + $FUNC.pipe($FS.writeFileSync($FIL, ...)); + message: >- + Insecure ZIP archive extraction can result in arbitrary path over write + and can result in code injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A5: Broken Access Control' + cwe: >- + CWE-22: Improper Limitation of a Pathname to a Restricted Directory + ('Path Traversal') + - id: zip_path_overwrite2 + patterns: + - pattern-either: + - pattern-inside: | + $X = require('unzip'); + ... + - pattern-inside: | + $X = require('unzipper'); + ... + - pattern-inside: | + $UNZIP.Parse(...).on('entry', function $FUNC($ENTRY) { + ... + }, ...); + - pattern-not: | + if ($FILENAME.indexOf('..')); + - pattern-not: > + $FS.createWriteStream($PATH.join(..., $PATH.basename($FILENAME, + ...))); + - pattern-not: | + $FS.writeFile($PATH.join(..., $PATH.basename($FILENAME, ...))); + - pattern-not: | + $FS.writeFileSync($PATH.join(..., $PATH.basename($FILENAME, ...))); + - pattern-either: + - pattern: | + $FS.createWriteStream($FIL, ...); + - pattern: | + $FS.writeFile($FIL, ...); + - pattern: | + $FS.writeFileSync($FIL, ...); + message: >- + Insecure ZIP archive extraction can result in arbitrary path over write + and can result in code injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A5: Broken Access Control' + cwe: >- + CWE-22: Improper Limitation of a Pathname to a Restricted Directory + ('Path Traversal') + - id: admzip_path_overwrite + patterns: + - pattern-inside: | + $X = require('adm-zip'); + ... + - pattern-not: | + if ($FILENAME.indexOf('..')); + - pattern-not: > + $FS.createWriteStream($PATH.join(..., $PATH.basename($FILENAME, + ...))); + - pattern-not: | + $FS.writeFile($PATH.join(..., $PATH.basename($FILENAME, ...))); + - pattern-not: | + $FS.writeFileSync($PATH.join(..., $PATH.basename($FILENAME, ...))); + - pattern-either: + - pattern: >- + $ZIPENTZ.forEach(function $FUNC($ENTRY, ...) { + $FS.createWriteStream(...); }, ...); + - pattern: >- + $ZIPENTZ.forEach(function $FUNC($ENTRY, ...) { $FS.writeFile(...); + }, ...); + - pattern: >- + $ZIPENTZ.forEach(function $FUNC($ENTRY, ...) { + $FS.writeFileSync(...); }, ...); + message: >- + Insecure ZIP archive extraction using adm-zip can result in arbitrary path + over write and can result in code injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A5: Broken Access Control' + cwe: >- + CWE-22: Improper Limitation of a Pathname to a Restricted Directory + ('Path Traversal') + - id: tar_path_overwrite + patterns: + - pattern-inside: | + $X = require('tar-stream'); + ... + - pattern-not-inside: | + $Y.pipe($UNZIP.Parse(...)).on('entry', function $FUNC(...) { + ... + }, ...); + - pattern-inside: | + $EXTRACT.on('entry', function $FUNC(...) { + ... + }, ...); + - pattern-not: | + if ($FILENAME.indexOf('..')); + - pattern-not: > + $FS.createWriteStream($PATH.join(..., $PATH.basename($FILENAME, + ...))); + - pattern-not: | + $FS.writeFile($PATH.join(..., $PATH.basename($FILENAME, ...))); + - pattern-not: | + $FS.writeFileSync($PATH.join(..., $PATH.basename($FILENAME, ...))); + - pattern-either: + - pattern: | + $FS.createWriteStream($FIL, ...); + - pattern: | + $FS.writeFile($FIL, ...); + - pattern: | + $FS.writeFileSync($FIL, ...); + message: >- + Insecure TAR archive extraction can result in arbitrary path over write + and can result in code injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A5: Broken Access Control' + cwe: >- + CWE-22: Improper Limitation of a Pathname to a Restricted Directory + ('Path Traversal') diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_node.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_node.ts new file mode 100644 index 0000000..d1a169e --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_node.ts @@ -0,0 +1,68 @@ +import crypto from "crypto"; + +var key = new Buffer('8CBDEC62EB4DCA778F842B02503011B2', 'hex') +var src = new Buffer('0002123401010100000000000000c631', 'hex') + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_aes_ecb +cipher = crypto.createCipheriv("aes-128-ecb", key, '') +cipher.setAutoPadding(false) +result = cipher.update(src).toString('hex'); +result += cipher.final().toString('hex'); +"result : " + result +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_sha1 +require("crypto") + .createHash("sha1") + .update("Man oh man do I love node!") + .digest("hex"); +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_md5 +require("crypto") + .createHash("md5") + .update("Man oh man do I love node!") + .digest("hex"); +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +function encrypt(text: any) { + let iv = crypto.randomBytes(IV_LENGTH); + // ruleid:node_aes_ecb + let cipher = crypto.createCipheriv('aes-256-ecb', Buffer.from(ENCRYPTION_KEY), iv); + // ruleid:node_aes_ecb + let cipher = crypto.createCipheriv('aes-192-ecb', Buffer.from(ENCRYPTION_KEY), iv); + // ruleid:node_aes_ecb + let cipher = crypto.createCipheriv('aes-128-ecb', Buffer.from(ENCRYPTION_KEY), iv); + let encrypted = cipher.update(text); + + encrypted = Buffer.concat([encrypted, cipher.final()]); + + return iv.toString('hex') + ':' + encrypted.toString('hex'); +} +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +function decrypt(text: string) { + let textParts = text.split(':'); + let iv = Buffer.from(textParts.shift(), 'hex'); + let encryptedText = Buffer.from(textParts.join(':'), 'hex'); + // ruleid:node_aes_ecb + let decipher = crypto.createDecipheriv('aes-128-ecb', Buffer.from(ENCRYPTION_KEY), iv); + let decrypted = decipher.update(encryptedText); +} +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_insecure_random_generator +crypto.pseudoRandomBytes(1); // +//Math based random insecure +// ruleid:node_insecure_random_generator +const val = Math.random(); +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_weak_crypto +var des = crypto.createCipher('des', key); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_node.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_node.yaml new file mode 100644 index 0000000..f595b43 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_node.yaml @@ -0,0 +1,72 @@ +rules: + - id: node_md5 + patterns: + - pattern: | + $X.createHash("md5") + message: >- + MD5 is a a weak hash which is known to have collision. Use a strong + hashing function. + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A9: Using Components with Known Vulnerabilities' + cwe: 'CWE-327: Use of a Broken or Risky Cryptographic Algorithm' + - id: node_sha1 + patterns: + - pattern: | + $X.createHash("sha1") + message: >- + SHA1 is a a weak hash which is known to have collision. Use a strong + hashing function. + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A9: Using Components with Known Vulnerabilities' + cwe: 'CWE-327: Use of a Broken or Risky Cryptographic Algorithm' + - id: node_aes_ecb + patterns: + - pattern-either: + - pattern: | + $X.createCipheriv("=~/aes-\([0-9]+\)-ecb/", ...) + - pattern: | + $X.createDecipheriv("=~/aes-\([0-9]+\)-ecb/", ...) + message: >- + AES with ECB mode is deterministic in nature and not suitable for + encrypting large amount of repetitive data. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A9: Using Components with Known Vulnerabilities' + cwe: 'CWE-327: Use of a Broken or Risky Cryptographic Algorithm' + - id: node_weak_crypto + patterns: + - pattern-either: + - pattern: | + $X.createCipher('des', ...) + message: >- + A weak or broken cryptographic algorithm was identified. Using these + functions will introduce vulnerabilities or downgrade the security of your application. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A9: Using Components with Known Vulnerabilities' + cwe: 'CWE-327: Use of a Broken or Risky Cryptographic Algorithm' + - id: node_insecure_random_generator + patterns: + - pattern-either: + - pattern: | + $X.pseudoRandomBytes(...) + - pattern: | + Math.random(...) + message: >- + crypto.pseudoRandomBytes()/Math.random() is a cryptographically weak random number generator. + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A9: Using Components with Known Vulnerabilities' + cwe: 'CWE-327: Use of a Broken or Risky Cryptographic Algorithm' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_timing_attacks.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_timing_attacks.ts new file mode 100644 index 0000000..b5e30ce --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/crypto_timing_attacks.ts @@ -0,0 +1,66 @@ +if (name == 'test') { + acces = 1; +} +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_timing_attack +if (password == 'mypass') { + correct = 1; +} +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_timing_attack +if ('test' == password) { + correct = 2; +} +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_timing_attack +if ('test' === password) { + correct = 2; +} +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +// ruleid:node_timing_attack +if (password == test) + x = 1; + +// {/fact} + + +// https://stackoverflow.com/a/47518578/2927282 +import { pbkdf2Sync, randomBytes } from 'crypto'; +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +export class Auth { + iters = 1e1; // TODO: increase later + keylen = 64; + digest = 'sha512'; + + create(password) { + const salt = randomBytes(128).toString('base64'); // <- salt + // salt was not base64 before being used by pbkdf2 + + const hash = pbkdf2Sync(password, salt, this.iters, this.keylen, this.digest).toString('base64'); + + return [salt, hash, this.iters].join('::'); + } + + verify(stored, password) { + const [salt, hash, iters] = stored.split('::'); + const verify = pbkdf2Sync(password, salt, parseInt(iters, 10), this.keylen, this.digest); + + // ruleid:node_timing_attack + return hash === verify.toString('base64'); + } +} +// {/fact} + +// {fact rule=cryptographic-key-generator@v1.0 defects=1} +function isAuthenticated(user, token) { + var correctToken = FetchUserTokenFromDB(user); + // ruleid:node_timing_attack + return token === correctToken; +} +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/error_disclosure.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/error_disclosure.yaml new file mode 100644 index 0000000..846f9da --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/error_disclosure.yaml @@ -0,0 +1,51 @@ +rules: + - id: node_error_disclosure + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $ERR = $ERROR.stack; + ... + $RES.end($ERR); + - pattern: | + $ERR = $ERROR.stack; + ... + $RES.send($ERR); + - pattern: | + $RES.end($ERR.stack) + - pattern: | + $RES.send($ERR.stack) + message: >- + Error messages with stack traces can expose sensitive information about + the application. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A3: Sensitive Data Exposure' + cwe: 'CWE-209: Generation of Error Message Containing Sensitive Information' + - id: generic_error_disclosure + patterns: + - pattern-either: + - pattern: | + console.trace(...) + - pattern: | + try { + ... + } catch($ERR){ + console.error(<... $ERR ...>, ...); + } + message: >- + Error messages with stack traces may expose sensitive information about + the application. + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A3: Sensitive Data Exposure' + cwe: 'CWE-209: Generation of Error Message Containing Sensitive Information' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/error_info_disclosure.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/error_info_disclosure.ts new file mode 100644 index 0000000..cf7ef71 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/error_info_disclosure.ts @@ -0,0 +1,31 @@ +app.get('/', function (req: any, res: { statusCode: number; setHeader: (arg0: string, arg1: string) => void; end: (arg0: any) => void; }) { + try { + foo; + } + // {fact rule=stack-trace-exposure@v1.0 defects=1} + + catch (err) { + res.statusCode = 500; + res.setHeader("Content-Type", "text/plain"); + // ruleid:node_error_disclosure + res.end(err.stack); + return; + } +}); +// {/fact} + +// {fact rule=stack-trace-exposure@v1.0 defects=1} + +// ruleid:generic_error_disclosure +try { + throw new Error("Something unexpected has occurred."); +} catch (e) { + console.error(e); +} +// {/fact} + +// {fact rule=stack-trace-exposure@v1.0 defects=1} + +// ruleid:generic_error_disclosure +console.trace("baad") +// {/fact} \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_deserialize.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_deserialize.ts new file mode 100644 index 0000000..25af440 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_deserialize.ts @@ -0,0 +1,35 @@ +var express = require('express'); +var cookieParser = require('cookie-parser'); +var escape = require('escape-html'); +var serialize = require('node-serialize'); +import serialize2 from 'serialize-to-js'; + + +var app = express(); +app.use(cookieParser()) +// {fact rule=untrusted-deserialization@v1.0 defects=1} +app.get('/', function (req: { cookies: { profile: any; }; }, res: { send: (arg0: string) => void; cookie: (arg0: string, arg1: string, arg2: { maxAge: number; httpOnly: boolean; }) => void; }) { + if (req.cookies.profile) { + var str = new Buffer(req.cookies.profile, 'base64').toString(); + // ruleid:node_deserialize + var obj = serialize.unserialize(str); + // ruleid:serializetojs_deserialize + serialize2.deserialize(str); + if (obj.username) { + res.send("Hello " + escape(obj.username)); + } + } else { + res.cookie('profile', "eyJ1c2VybmFtZSI6ImFqaW4iLCJjb3VudHJ5IjoiaW5kaWEiLCJjaXR5IjoiYmFuZ2Fsb3JlIn0=", { + maxAge: 900000, + httpOnly: true + }); + } + res.send("Hello World"); +}); +// {/fact} + +// {fact rule=untrusted-deserialization@v1.0 defects=1} +app.listen(3000); +// ruleid:serializetojs_deserialize +require('serialize-to-js').deserialize(str); +// {/fact} \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_deserialize.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_deserialize.yaml new file mode 100644 index 0000000..3d13a59 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_deserialize.yaml @@ -0,0 +1,33 @@ +rules: + - id: serializetojs_deserialize + patterns: + - pattern-inside: | + require('serialize-to-js'); + ... + - pattern: | + $X.deserialize(...) + message: >- + User controlled data in 'unserialize()' or 'deserialize()' function can + result in Object Injection or Remote Code Injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A8: Insecure Deserialization' + cwe: 'CWE-502: Deserialization of Untrusted Data' + - id: node_deserialize + patterns: + - pattern-inside: | + require('node-serialize'); + ... + - pattern: | + $X.unserialize(...) + message: >- + User controlled data in 'unserialize()' or 'deserialize()' function can + result in Object Injection or Remote Code Injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A8: Insecure Deserialization' + cwe: 'CWE-502: Deserialization of Untrusted Data' \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_node.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_node.ts new file mode 100644 index 0000000..5bbfa11 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_node.ts @@ -0,0 +1,31 @@ +var express = require('express'); +var app = express(); +app.get('/', function (req: { query: { name: string; }; body: { name: string; }; }, res: { send: (arg0: string) => void; }) { + // {fact rule=code-injection@v1.0 defects=1} + // ruleid:eval_nodejs + var resp = eval("(" + req.query.name + ")"); +// {/fact} + + // {fact rule=code-injection@v1.0 defects=1} + // ruleid:eval_nodejs + var z = new Function('arg1', 'arg2', req.query.name) + z(1, 2); +// {/fact} + + // {fact rule=code-injection@v1.0 defects=1} + // ruleid:eval_nodejs + setTimeout('alert(' + req.body.name, 0); +// {/fact} + + // {fact rule=code-injection@v1.0 defects=1} + // ruleid:eval_nodejs + setInterval(req.body.name, 0); + res.send('Response
'); +}); +// {/fact} + +app.listen(8000); +eval("outside_express" + req.foo) +setTimeout('alert(' + req.body.name, 0); +setInterval(req.body.name, 0); +new Function('arg1', 'arg2', req.query.name) \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_node.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_node.yaml new file mode 100644 index 0000000..375450a --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_node.yaml @@ -0,0 +1,69 @@ +rules: + - id: eval_nodejs + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + new Function(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + new Function(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + eval(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + eval(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + setTimeout(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + setTimeout(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + setInterval(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + setInterval(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + new Function(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + new Function(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + eval(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + eval(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + setTimeout(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + setTimeout(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + setInterval(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + setInterval(..., <... $INP ...>, ...); + message: >- + User controlled data in eval() or similar functions may result in Server + Side Injection or Remote Code Injection + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-95: Improper Neutralization of Directives in Dynamically Evaluated + Code ('Eval Injection') \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_yaml_deserialize.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_yaml_deserialize.ts new file mode 100644 index 0000000..a1a4100 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_yaml_deserialize.ts @@ -0,0 +1,24 @@ +var untrusted_code = '"toString": ! "function (){very_evil_thing();}"'; +var notneeded = 1; +// {fact rule=untrusted-deserialization@v1.0 defects=1} + +// I'm just converting that string, what could possibly go wrong? +// ruleid:yaml_deserialize +require('js-yaml').load(untrusted_code) + '' +// {/fact} + + +var yaml = require('js-yaml') + +import yaml2 from 'js-yaml'; +// {fact rule=untrusted-deserialization@v1.0 defects=1} + +// ruleid:yaml_deserialize +yaml.load(untrusted_code) +// {/fact} + +// {fact rule=untrusted-deserialization@v1.0 defects=1} + +// ruleid:yaml_deserialize +yaml2.load(untrusted_code) +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_yaml_deserialize.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_yaml_deserialize.yaml new file mode 100644 index 0000000..5ef6b08 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/eval_yaml_deserialize.yaml @@ -0,0 +1,17 @@ +rules: + - id: yaml_deserialize + patterns: + - pattern-inside: | + require('js-yaml'); + ... + - pattern: | + $X.load(...) + message: >- + User controlled data in 'yaml.load()' function can result in Remote Code + Injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A8: Insecure Deserialization' + cwe: 'CWE-502: Deserialization of Untrusted Data' \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/exec_os_command.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/exec_os_command.ts new file mode 100644 index 0000000..5c4289a --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/exec_os_command.ts @@ -0,0 +1,140 @@ + +import { exec, spawn } from 'child_process'; + +// {fact rule=os-command-injection@v1.0 defects=1} +router.post('/ping', (req: { body: { url: any; }; }, res: { send: (arg0: string) => void; }) => { + // ruleid:generic_os_command_exec2 + exec(`${req.body.url}`, (error) => { + if (error) { + return res.send('error'); + } + res.send('pong') + }) +// {/fact} + + +}) +// {fact rule=os-command-injection@v1.0 defects=1} +router.post('/gzip', (req: { query: { file_path: string; }; }, res: { send: (arg0: string) => void; }) => { + // ruleid:generic_os_command_exec2 + exec( + 'gzip ' + req.query.file_path, + function (err, data) { + console.log('err: ', err) + console.log('data: ', data); + res.send('done'); + }); +}) +// {/fact} + +// {fact rule=os-command-injection@v1.0 defects=1} +var child_process = require('child_process'); +var x = 1; +app.get('/', function (req: { query: { file_path: string; ping: any; }; }, res: { send: (arg0: string) => void; }) { + // ruleid:generic_os_command_exec + child_process.exec( + req.query.file_path, + function (err: any, data: any) { + console.log('err: ', err) + console.log('data: ', data); + }); +// {/fact} + +// {fact rule=os-command-injection@v1.0 defects=1} + // ruleid:generic_os_command_exec + child_process.exec('gzip' + + req.query.file_path, + function (err: any, data: any) { + console.log('err: ', err) + console.log('data: ', data); + }); +// {/fact} + +// {fact rule=os-command-injection@v1.0 defects=1} + // ruleid:generic_os_command_exec + child_process.exec('foobar' + + req.query.file_path + "asdD", + function (err: any, data: any) { + console.log('err: ', err) + console.log('data: ', data); + }); +// {/fact} + +// {fact rule=os-command-injection@v1.0 defects=1} + // ruleid:generic_os_command_exec + child_process.exec( + req.query.file_path + "asdD", + function (err: any, data: any) { + console.log('err: ', err) + console.log('data: ', data); + }); +// {/fact} + +// {fact rule=os-command-injection@v1.0 defects=1} + //Do not detect this + child_process.exec( + foo + "asdD", + function (err: any, data: any) { + console.log('err: ', err) + console.log('data: ', data); + }); +// {/fact} + + + // ruleid:generic_os_command_exec + child_process.execSync( + req.query.file_path + 'rsync -avAXz --info=progress2 "/src" "/dest"', + { stdio: 'inherit' }); + + res.send('Hello World!') +// {/fact} + + +// {fact rule=os-command-injection@v1.0 defects=1} + // ruleid:generic_os_command_exec + var foo = req.query.ping; + var x; + child_process.exec('ping -c 2 ' + foo, function (err: any, data: any) { + response.end(); + }); +}) +// {/fact} + +// {fact rule=os-command-injection@v1.0 defects=1} +var foo = '1'; +require('child_process').exec(foo + 'info=progress2 "/src" "/dest"'); + + +const router = require('express').Router(); +import exe from 'child_process'; + +router.post('/', function (req: { body: { dir: string; }; }, res: { json: (arg0: { message: any; }) => void; status: (arg0: number) => { (): any; new(): any; json: { (arg0: { message: any; }): void; new(): any; }; }; }) { + // ruleid:generic_os_command_exec + exe.exec('ls ' + req.body.dir, function (err: any, data: any) { + if (!err) { + res.json({ message: data }); + } else { + res.status(500).json({ message: err }); + } + }); +}); +// {/fact} + +// {fact rule=os-command-injection@v1.0 defects=1} +module.exports = router; + + +var http = require("http"); +var url = require("url"); +var exe = require('child_process'); +http.createServer(function (request: { url: any; }, response: { end: () => void; }) { + // ruleid:generic_os_command_exec + var parsedUrl = url.parse(request.url, true); + exe.exec('ping -c 2 ' + parsedUrl.query.ping, function (err: any, data: any) { + response.end(); + }); + +}).listen(8888); +// {/fact} + + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/exec_os_command.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/exec_os_command.yaml new file mode 100644 index 0000000..b97b7b8 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/exec_os_command.yaml @@ -0,0 +1,91 @@ +rules: + - id: generic_os_command_exec + patterns: + - pattern-inside: | + $EXEC = require('child_process'); + ... + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $EXEC.exec(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $EXEC.exec(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $EXEC.execSync(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $EXEC.execSync(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + $EXEC.exec(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $EXEC.exec(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $EXEC.execSync(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + $EXEC.execSync(..., <... $INP ...>, ...); + message: >- + User controlled data in 'child_process.exec()' can result in Remote OS + Command Execution. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-78: Improper Neutralization of Special Elements used in an OS + Command ('OS Command Injection') + - id: generic_os_command_exec2 + patterns: + - pattern-inside: | + var {$EXEC} = require('child_process'); + ... + - pattern-inside: | + $APP.$METHOD(..., function $FUNC($REQ, $RES, ...){ ... }); + - pattern-either: + - pattern: | + exec(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + exec(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + execSync(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + execSync(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + exec(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + exec(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + execSync(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + execSync(..., <... $INP ...>, ...); + message: >- + User controlled data in 'child_process.exec()' can result in Remote OS + Command Execution. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-78: Improper Neutralization of Special Elements used in an OS + Command ('OS Command Injection') diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/express_bodyparser_dos.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/express_bodyparser_dos.ts new file mode 100644 index 0000000..ace0b58 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/express_bodyparser_dos.ts @@ -0,0 +1,18 @@ +const express = require('express') + , cors = require('cors') + , bodyParser = require('body-parser'); + +var app = express(); + +// {fact rule=resource-leak@v1.0 defects=1} +app.configure(function () { + app.set('port', process.env.PORT || 3000); + app.set('views', __dirname + '/views'); + app.set('view engine', 'jade'); + app.use(express.favicon()); + app.use(express.logger('dev')); + // ruleid:express_bodyparser + app.use(express.bodyParser()); + app.use(cors()); +}); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/express_bodyparser_dos.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/express_bodyparser_dos.yaml new file mode 100644 index 0000000..22c223e --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/express_bodyparser_dos.yaml @@ -0,0 +1,19 @@ +rules: + - id: express_bodyparser + patterns: + - pattern-inside: + $APP = express(); + ... + - pattern-inside: | + $APP.use(...); + - pattern: + $X.bodyParser(...) + message: >- + POST Request to Express Body Parser 'bodyParser()' can create Temporary + files and consume space. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A9: Using Components with Known Vulnerabilities' + cwe: 'CWE-400: Uncontrolled Resource Consumption' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_anti_csrf.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_anti_csrf.yaml new file mode 100644 index 0000000..23d57c3 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_anti_csrf.yaml @@ -0,0 +1,19 @@ +rules: + - id: anti_csrf_control + patterns: + - pattern-inside: | + $CSRUF = require('csurf'); + ... + - pattern-either: + - pattern: + $X = csrf(...); + - pattern: + $X = csurf(...); + - pattern: + $APP.use(csrf(...)); + - pattern: + $APP.use(csurf(...)); + message: 'This application has anti CSRF protection which prevents cross site request forgery attacks.' + languages: + - javascript + severity: WARNING \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_helmet_checks.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_helmet_checks.yaml new file mode 100644 index 0000000..bbd9a4e --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_helmet_checks.yaml @@ -0,0 +1,236 @@ +# Convert this to INFO when semgrep supports that +rules: + - id: helmet_header_check_csp + message: >- + Content Security Policy header is present. More Information: + https://helmetjs.github.io/docs/csp/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {contentSecurityPolicy: false}, ...) + - pattern-either: + - pattern: | + helmet({contentSecurityPolicy: {directives: ...}}) + - pattern: | + helmet.contentSecurityPolicy({directives: ...}) + - pattern: | + csp({directives: ...}) + - id: helmet_header_check_crossdomain + message: >- + X-Permitted-Cross-Domain-Policies header set to off. More information: + https://helmetjs.github.io/docs/crossdomain/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {permittedCrossDomainPolicies: false}, ...) + - pattern-either: + - pattern: | + permittedCrossDomainPolicies() + - pattern: | + permittedCrossDomainPolicies({ permittedPolicies: ... }) + - pattern: | + helmet.permittedCrossDomainPolicies({ permittedPolicies: ... }) + - pattern: | + helmet({permittedCrossDomainPolicies: { permittedPolicies: ... }}) + - pattern: | + helmet.permittedCrossDomainPolicies() + - id: helmet_header_check_expect_ct + message: >- + Expect-CT header is present. More information: + https://helmetjs.github.io/docs/expect-ct/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {expectCt: false}, ...) + - pattern-either: + - pattern: | + expectCt({maxAge: ...,}) + - pattern: | + helmet.expectCt({maxAge: ...,}) + - pattern: | + expectCt({enforce: ...,}) + - pattern: | + hemlet.expectCt({enforce: ...,}) + - pattern: | + helmet({expectCt: { enforce: ... }}) + - id: helmet_header_feature_policy + message: >- + Feature-Policy header is present. More information: + https://helmetjs.github.io/docs/feature-policy/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {featurePolicy: false}, ...) + - pattern-either: + - pattern: | + featurePolicy(..., {features: ...}, ...) + - pattern: | + helmet.featurePolicy(..., {features: ...}, ...) + - pattern: | + helmet({featurePolicy: {features: ...}}) + - id: helmet_header_frame_guard + message: >- + X-Frame-Options header is present. More information: + https://helmetjs.github.io/docs/frameguard/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {frameguard: false}, ...) + - pattern-either: + - pattern: | + $APP.use(hemlet()) + - pattern: | + helmet.frameguard(...) + - pattern: | + frameguard(...) + - pattern: | + helmet({frameguard: ...}) + - id: helmet_header_dns_prefetch + message: >- + X-DNS-Prefetch-Control header is present and DNS Prefetch Control is + enabled. More information: + https://helmetjs.github.io/docs/dns-prefetch-control/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {dnsPrefetchControl: false}, ...) + - pattern-either: + - pattern: | + $APP.use(helmet()) + - pattern: | + helmet.dnsPrefetchControl() + - pattern: | + dnsPrefetchControl() + - pattern: | + helmet.dnsPrefetchControl({ allow: false }) + - pattern: | + helmet({dnsPrefetchControl: {allow: false}}) + - pattern: | + dnsPrefetchControl({ allow: false }) + - id: helmet_header_x_powered_by + message: >- + Default X-Powered-By is removed or modified. More information: + https://helmetjs.github.io/docs/hide-powered-by/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {hidePoweredBy: false}, ...) + - pattern-either: + - pattern: | + $APP.use(helmet()) + - pattern: | + app.disable('x-powered-by') + - pattern: | + helmet.hidePoweredBy(...) + - pattern: | + hidePoweredBy(...) + - pattern: | + helmet({hidePoweredBy: ...}) + - id: helmet_header_hsts + message: >- + HSTS header is present. More information: + https://helmetjs.github.io/docs/hsts/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {hsts: false}, ...) + - pattern-either: + - pattern: | + $APP.use(helmet()) + - pattern: | + helmet.hsts(...) + - pattern: | + hsts({ maxAge: ...}) + - pattern: | + helmet({hsts: ...}) + - id: helmet_header_ienoopen + message: >- + X-Download-Options header is present. More information: + https://helmetjs.github.io/docs/ienoopen/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {ieNoOpen: false}, ...) + - pattern-either: + - pattern: | + $APP.use(helmet()) + - pattern: | + helmet.ieNoOpen() + - pattern: | + ieNoOpen() + - pattern: | + helmet({ieNoOpen: ...}) + - id: helmet_header_nosniff + message: >- + Content-Type-Options header is present. More information: + https://helmetjs.github.io/docs/dont-sniff-mimetype/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {noSniff: false}, ...) + - pattern-either: + - pattern: | + $APP.use(helmet()) + - pattern: | + helmet.noSniff() + - pattern: | + noSniff() + - pattern: | + helmet({noSniff: ...}) + - id: helmet_header_referrer_policy + message: >- + Referrer-Policy header is present. More information: + https://helmetjs.github.io/docs/referrer-policy/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {referrerPolicy: false}, ...) + - pattern-either: + - pattern: | + helmet.referrerPolicy(...) + - pattern: | + referrerPolicy(...) + - pattern: | + helmet({referrerPolicy: ...}) + - id: helmet_header_xss_filter + message: >- + X-XSS-Protection header is present. More information: + https://helmetjs.github.io/docs/xss-filter/ + languages: + - javascript + severity: WARNING + patterns: + - pattern-not: | + $HELMET(..., {xssFilter: false}, ...) + - pattern-either: + - pattern: | + $APP.use(helmet()) + - pattern: | + helmet.xssFilter(...) + - pattern: | + xssFilter(...) + - pattern: | + helmet({xssFilter: ...}) + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_ratelimiting.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_ratelimiting.yaml new file mode 100644 index 0000000..aba6c0f --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/good_ratelimiting.yaml @@ -0,0 +1,14 @@ +rules: + - id: rate_limit_control + patterns: + - pattern-either: + - pattern: + require("express-rate-limit"); + - pattern: + require("express-limiter"); + - pattern: + require("@authentication/rate-limit"); + message: 'This application has API rate limiting controls.' + languages: + - javascript + severity: WARNING diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_jwt.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_jwt.ts new file mode 100644 index 0000000..f04d8df --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_jwt.ts @@ -0,0 +1,150 @@ +// {fact rule=hardcoded-credentials@v1.0 defects=1} +// ruleid:hardcoded_jwt_secret +import jsonwt from 'jsonwebtoken' +import jose from 'jose' +const { JWK, JWT } = jose +import config from './config' + +const payload = { foo: 'bar' } +const secret = 'shhhhh' + +const secret2 = config.secret +const secret3 = process.env.SECRET || 'fallback-secret' +// {/fact} + + +// {fact rule=hardcoded-credentials@v1.0 defects=1} +//jsonwebtoken +//true +const token1 = jsonwt.sign(payload, secret) +// {/fact} + +// {fact rule=hardcoded-credentials@v1.0 defects=1} +//true +const token2 = jsonwt.sign(payload, 'some-secret') +// {fact rule=hardcoded-credentials@v1.0 defects=1} +//?? +const token5 = jsonwt.sign(payload, secret3) +// {/fact} + +// {fact rule=hardcoded-credentials@v1.0 defects=1} +//jose +//true +const token6 = JWT.sign(payload, JWK.asKey(secret)) +// {/fact} + +// {fact rule=hardcoded-credentials@v1.0 defects=1} +//true +const token7 = JWT.sign(payload, JWK.asKey('raz-dva-tri')) +// {/fact} + +// {fact rule=hardcoded-credentials@v1.0 defects=1} +//true +const token8 = JWT.sign(payload, secret) +// {/fact} + +// {fact rule=hardcoded-credentials@v1.0 defects=1} +//true +const token9 = JWT.sign(payload, 'secret-again') +// {/fact} + + + +// {fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:hardcoded_jwt_secret +import $jwt from 'jsonwebtoken' + +const cert = 'hardcoded-secret'; + +module.exports = (app: { post: (arg0: string, arg1: (req: any, res: any) => void) => void; login: (arg0: any, arg1: any) => Promise }) => { + app.post('/api/login', (req: { body: { username: any; password: any } }, res: { send: (arg0: any) => void; status: (arg0: number) => { (): any; new(): any; send: { (arg0: any): void; new(): any } } }) => { + app.login(req.body.username, req.body.password).then((out: { token: any }) => { + out.token = $jwt.sign(out, cert, { expiresIn: '1d' }); + res.send(out); + }, (err: any) => { + console.error(err); + res.status(400).send(err); + }); + }); +}; +// {/fact} + +// {fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:hardcoded_jwt_secret +import jwt from 'jsonwebtoken' + +const jwtSign = (payload = { id: 1 }) => + jwt.sign(payload, 'hardcoded-secret') + +const jwtVerify = (req: { headers: { [x: string]: any } }) => () => new Promise((resolve, reject) => { + const token = req.headers['x-access-token'] + if (!token) { + resolve(false) + } + jwt.verify(token, 'hardcoded-secret', (err: any, decoded: unknown) => { + if (err) { + resolve(false) + } + resolve(decoded) + }) +}) +// {/fact} + +// {fact rule=hardcoded-credentials@v1.0 defects=1} + +export default { jwtSign, jwtVerify } + (() => { + + 'use strict'; + + // ruleid:hardcoded_jwt_secret + let User = require('./user'), + jwt = require('jsonwebtoken'); + + const express = require('express'); + let router = express.Router(); + + router.post('/signup', (req: { body: { name: any; password: any } }, res: { send: (arg0: { success: boolean; token: any }) => void }) => { + let user = new User({ + name: req.body.name, + password: req.body.password + }); + var token = jwt.sign(user, "hardcoded-secret", { expiresIn: 60 * 60 * 10 }); + res.send({ success: true, token: token }); + }); + + module.exports = router; + })(); +// {/fact} + +// {fact rule=hardcoded-credentials@v1.0 defects=1} + +'use strict'; +import config from './app.config' +const privateMethods = { + initialize(USER: { findOne: (arg0: {}) => { (): any; new(): any; exec: { (arg0: (error: any, user: any) => any): void; new(): any } } }) { + // ruleid:hardcoded_jwt_secret + const router = require('express').Router(), + jwt = require('jsonwebtoken'); + if (config) { + router.route('/register').post((req: any, res: { status: (arg0: number) => { (): any; new(): any; send: { (arg0: { error: any }): any; new(): any }; json: { (arg0: { token: any }): any; new(): any } } }) => { + USER.findOne({}).exec((error: any, user: { save: (arg0: (error: any, user: any) => any) => void }) => { + if (error) + return res.status(400).send({ error: error }); + user.save((error: any, user: { _id: any }) => { + if (error) { + return res.status(400).send({ error: error }); + } else { + const token = jwt.sign({ id: user._id }, 'hardcoded-secret'); + return res.status(201).json({ token: token }); + } + }); + }); + }); + } + } +}; +module.exports = privateMethods; +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_jwt.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_jwt.yaml new file mode 100644 index 0000000..f398378 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_jwt.yaml @@ -0,0 +1,73 @@ +# Rule is from https://github.com/returntocorp/semgrep-rules/blob/develop/javascript/jwt-hardcode/jwt-hardcode.yaml +# module imports used as described in https://github.com/returntocorp/semgrep/issues/285 +rules: + - id: hardcoded_jwt_secret + patterns: + - pattern-either: + - pattern: | + $JWT = require("jsonwebtoken"); + ... + $JWT.sign($P, "...", ...); + - pattern: | + $JWT = require("jsonwebtoken"); + ... + $JWT.verify($P, "...", ...); + - pattern: | + $JWT = require("jsonwebtoken"); + ... + $SECRET = "..."; + ... + $JWT.sign($P, $SECRET, ...); + - pattern: | + $JWT = require("jsonwebtoken"); + ... + $SECRET = "..."; + ... + $JWT.verify($P, $SECRET, ...); + - pattern: | + $JOSE = require("jose"); + ... + $JOSE.JWT.sign($P, "...", ...); + - pattern: | + $JOSE = require("jose"); + ... + $JOSE.JWT.verify($P, "...", ...); + - pattern: | + $JOSE = require("jose"); + ... + $JOSE.JWT.sign($P, $JOSE.JWK.asKey("..."), ...); + - pattern: | + $JOSE = require("jose"); + ... + $JOSE.JWT.verify($P, $JOSE.JWK.asKey("..."), ...); + - pattern: | + $JOSE = require("jose"); + ... + $SECRET = "..."; + ... + $JOSE.JWT.sign($P, $SECRET, ...); + - pattern: | + $JOSE = require("jose"); + ... + $SECRET = "..."; + ... + $JOSE.JWT.verify($P, $SECRET, ...); + - pattern: | + $JOSE = require("jose"); + ... + $SECRET = "..."; + ... + $JOSE.JWT.sign($P, $JOSE.JWK.asKey($SECRET), ...); + - pattern: | + $JOSE = require("jose"); + ... + $SECRET = "..."; + ... + $JOSE.JWT.verify($P, $JOSE.JWK.asKey($SECRET), ...); + message: Hardcoded JWT secret was found + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A3: Sensitive Data Exposure' + cwe: 'CWE-798: Use of Hard-coded Credentials' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_secrets.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_secrets.ts new file mode 100644 index 0000000..95e0a5b --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_secrets.ts @@ -0,0 +1,68 @@ +// Case need to be removed from GT. Already covered by ‘CredSweeper’. + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:node_password +password = '1212'; +x = 1; +password = x; +pass = 123; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:node_password +PASSWORD = '12211'; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:node_password +obj['password'] = '121233'; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:node_password +obj2.password = '1234'; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:node_password +obj2.pass = '1234'; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:node_password +obj2["pass"] = '1234'; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + + +// ruleid:node_password +const password = '1212'; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:node_password +let password = '1212'; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + +// ruleid:node_password +var password = '1212'; +// {/ex-fact} + +// {ex-fact rule=hardcoded-credentials@v1.0 defects=1} + + +// ruleid:node_api_key +angular.module('starter.services', []) + .constant('api_key', '6e906986c3b199c51fff3154cfb76979') +this.apiUrl = api_url; +// {/ex-fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_secrets.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_secrets.yaml new file mode 100644 index 0000000..709e90e --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/hardcoded_secrets.yaml @@ -0,0 +1,185 @@ +rules: + - id: node_password + patterns: + - pattern-not: password = '' + - pattern-not: PASSWORD = '' + - pattern-not: PASS = '' + - pattern-not: pass = '' + - pattern-not: $X[...] = '' + - pattern-either: + - pattern: | + password = '...'; + - pattern: | + PASSWORD = '...'; + - pattern: | + PASS = '...'; + - pattern: | + pass = '...'; + - pattern: | + $X['pass'] = '...'; + - pattern: | + $X['password'] = '...'; + - pattern: | + $X['PASS'] = '...'; + - pattern: | + $X['PASSWORD'] = '...'; + - pattern: | + $X.pass = '...'; + - pattern: | + $X.password = '...'; + - pattern: | + $X.PASS = '...'; + - pattern: | + $X.PASSWORD = '...'; + message: >- + A hardcoded password in plain text is identified. Store it properly in an + environment variable. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A3: Sensitive Data Exposure' + cwe: 'CWE-798: Use of Hard-coded Credentials' + - id: node_secret + patterns: + - pattern-not: secret = '' + - pattern-not: SECRET = '' + - pattern-not: api_secret = '' + - pattern-not: API_SECRET = '' + - pattern-not: $X['...'] = '' + - pattern-either: + - pattern: | + secret = '...'; + - pattern: | + SECRET = '...'; + - pattern: | + api_secret = '...'; + - pattern: | + API_SECRET = '...'; + - pattern: | + $X['secret'] = '...'; + - pattern: | + $X['SECRET'] = '...'; + - pattern: | + $X['api_secret'] = '...'; + - pattern: | + $X['apiSecret'] = '...'; + - pattern: | + $X['API_SECRET'] = '...'; + - pattern: | + $X.secret = '...'; + - pattern: | + $X.SECRET = '...'; + - pattern: | + $X.api_secret = '...'; + - pattern: | + $X.apiSecret = '...'; + - pattern: | + $X.API_SECRET = '...'; + - pattern: | + $X('api_secret', '...') + - pattern: | + $X('apiSecret', '...') + - pattern: | + $X('API_SECRET', '...') + - pattern: | + $X('secret', '...') + - pattern: | + $X('SECRET', '...') + message: >- + A hardcoded secret is identified. Store it properly in an + environment variable. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A3: Sensitive Data Exposure' + cwe: 'CWE-798: Use of Hard-coded Credentials' + - id: node_username + patterns: + - pattern-not: username = '' + - pattern-not: userName = '' + - pattern-not: USERNAME = '' + - pattern-not: user = '' + - pattern-not: USER = '' + - pattern-not: $X['...'] = '' + - pattern-either: + - pattern: | + username = '...'; + - pattern: | + userName = '...'; + - pattern: | + USERNAME = '...'; + - pattern: | + user = '...'; + - pattern: | + USER = '...'; + - pattern: | + $X['username'] = '...'; + - pattern: | + $X['userName'] = '...'; + - pattern: | + $X['USERNAME'] = '...'; + - pattern: | + $X['user'] = '...'; + - pattern: | + $X['USER'] = '...'; + - pattern: | + $X.username = '...'; + - pattern: | + $X.userName = '...'; + - pattern: | + $X.USERNAME = '...'; + - pattern: | + $X.user = '...'; + - pattern: | + $X.USER = '...'; + message: >- + A hardcoded username in plain text is identified. Store it properly in an + environment variable. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A3: Sensitive Data Exposure' + cwe: 'CWE-798: Use of Hard-coded Credentials' + - id: node_api_key + patterns: + - pattern-not: api_key = '' + - pattern-not: apiKey = '' + - pattern-not: API_KEY = '' + - pattern-not: $X['...'] = '' + - pattern-either: + - pattern: | + api_key = '...'; + - pattern: | + apiKey = '...'; + - pattern: | + API_KEY = '...'; + - pattern: | + $X['api_key'] = '...'; + - pattern: | + $X['apiKey'] = '...'; + - pattern: | + $X['API_KEY'] = '...'; + - pattern: | + $X.api_key = '...'; + - pattern: | + $X.apiKey = '...'; + - pattern: | + $X.API_KEY = '...'; + - pattern: | + $X('api_key', '...') + - pattern: | + $X('apiKey', '...') + - pattern: | + $X('API_KEY', '...') + message: >- + A hardcoded API Key is identified. Store it properly in an + environment variable. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A3: Sensitive Data Exposure' + cwe: 'CWE-798: Use of Hard-coded Credentials' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_cors_star.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_cors_star.ts new file mode 100644 index 0000000..8c0d45c --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_cors_star.ts @@ -0,0 +1,61 @@ +import express from 'express'; + +const app = express(); + +// {fact rule=origin-validation-error@v1.0 defects=1} +// ruleid:generic_cors +app.options('*', cors()) +app.get('/', function (req: any, res: { set: (arg0: any) => void; }) { + + res.set(ffff) +}); +// {/fact} + + +app.get('/', function (req: any, res: { writeHead: (arg0: number, arg1: { "Access-Control-Allow-Origin": string; }) => void; set: (arg0: string, arg1: string | null | undefined) => void; }) { + var y = 1; + // ruleid:express_cors + var x = '*'; + + //sgrep bug - https://github.com/returntocorp/sgrep/issues/512 +// {fact rule=origin-validation-error@v1.0 defects=1} + // ruleid:express_cors + res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); +// {/fact} + + // ruleid:express_cors +// {fact rule=origin-validation-error@v1.0 defects=1} + res.set('access-control-allow-origin', '*'); +// {/fact} + + //do not match - sgrep bug -rewrite-rule +// {fact rule=origin-validation-error@v1.0 defects=0} + res.set('Access-Control-Allow-Origin', 'google.com'); +// {/fact} + + // ruleid:express_cors + res.set('Access-Control-Allow-Origin', '*'); +// {/fact} + +// {fact rule=origin-validation-error@v1.0 defects=1} + // ruleid:express_cors + res.set({ + 'Content-Length': 123, + 'access-control-allow-origin': '*', + 'ETag': '12345' + }) +// {/fact} + +// {fact rule=origin-validation-error@v1.0 defects=1} + // ruleid:express_cors + res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }) + + res.set('access-control-allow-origin', x); + + // do not detect - sgrep bug + res.set('access-control-allow-origin', 'xyz.com'); + //do not detect - sgrep bug + res.set('access-control-allow-origin', null); + +}); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_cors_star.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_cors_star.yaml new file mode 100644 index 0000000..6fa49b9 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_cors_star.yaml @@ -0,0 +1,71 @@ +# Need QA + sgrep bug fix + false positive in generic_2 and {"=~/[Access-Control-Allow-Origin|access-control-allow-origin]/": '*' } not working +rules: + - id: generic_cors + patterns: + - pattern: | + $APP.options('*', cors(...)) + message: >- + Access-Control-Allow-Origin response header is set to "*". This will + disable CORS Same Origin Policy restrictions. + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: 'CWE-346: Origin Validation Error' + - id: express_cors + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $APP.options('*', cors(...)) + - pattern: > + $RES.set("=~/[Access-Control-Allow-Origin|access-control-allow-origin]/", + '*', ...) + - pattern: > + $RES.set(..., { + "=~/[Access-Control-Allow-Origin|access-control-allow-origin]/" : + '*' }, ...) + - pattern: > + $RES.header("=~/[Access-Control-Allow-Origin|access-control-allow-origin]/", + '*', ...) + - pattern: > + $RES.writeHead(..., + {"=~/[Access-Control-Allow-Origin|access-control-allow-origin]/": + '*' }, ...); + - pattern: > + $VAL = '*'; + ... + $RES.set("=~/[Access-Control-Allow-Origin|access-control-allow-origin]/", + $VAL, ...); + - pattern: > + $VAL = '*'; + ... + $RES.set(..., { + "=~/[Access-Control-Allow-Origin|access-control-allow-origin]/" : + $VAL }, ...); + - pattern: > + $VAL = '*'; + ... + $RES.header("=~/[Access-Control-Allow-Origin|access-control-allow-origin]/", + $VAL, ...); + - pattern: > + $VAL = '*'; + ... + $RES.writeHead(..., + {"=~/[Access-Control-Allow-Origin|access-control-allow-origin]/": + $VAL }, ...); + message: >- + Access-Control-Allow-Origin response header is set to "*". This will + disable CORS Same Origin Policy restrictions. + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: 'CWE-346: Origin Validation Error' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_helmet_disabled.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_helmet_disabled.ts new file mode 100644 index 0000000..8e4b6f9 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_helmet_disabled.ts @@ -0,0 +1,14 @@ +// {fact rule=protection-mechanism-failure@v1.0 defects=1} +// ruleid:helmet_feature_disabled +app.use(helmet({ + frameguard: false, +})) +// {/fact} + + +// {fact rule=protection-mechanism-failure@v1.0 defects=1} +// ruleid:helmet_feature_disabled +app.use(helmet({ + "xssFilter": false +})) +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_helmet_disabled.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_helmet_disabled.yaml new file mode 100644 index 0000000..0f2b67a --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_helmet_disabled.yaml @@ -0,0 +1,36 @@ +rules: + - id: helmet_feature_disabled + patterns: + - pattern-either: + - pattern: | + $HELMET(..., {frameguard: false}, ...) + - pattern: | + $HELMET(..., {contentSecurityPolicy: false}, ...) + - pattern: | + $HELMET(..., {permittedCrossDomainPolicies: false}, ...) + - pattern: | + $HELMET(..., {dnsPrefetchControl: false}, ...) + - pattern: | + $HELMET(..., {expectCt: false}, ...) + - pattern: | + $HELMET(..., {featurePolicy: false}, ...) + - pattern: | + $HELMET(..., {hsts: false}, ...) + - pattern: | + $HELMET(..., {ieNoOpen: false}, ...) + - pattern: | + $HELMET(..., {noSniff: false}, ...) + - pattern: | + $HELMET(..., {hidePoweredBy: false}, ...) + - pattern: | + $HELMET(..., {referrerPolicy: false}, ...) + - pattern: | + $HELMET(..., {xssFilter: false}, ...) + message: >- + One or more Security Response header is explicitly disabled in Helmet. + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: 'CWE-693: Protection Mechanism Failure' \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_injection.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_injection.ts new file mode 100644 index 0000000..4c56303 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_injection.ts @@ -0,0 +1,105 @@ +var http = require('http'); + +var server = http.createServer(function (req: { foo: string; }, res: { writeHead: (arg0: number, arg1: { test: any; foo?: any; }) => void; end: (arg0: string) => void; }) { + var bla = 'dsdsd'; + switch (testIndex++) { + // {fact rule=neutralization-of-http@v1.0 defects=1} + case 0: + // ruleid:generic_header_injection + res.writeHead(200, { test: 'foo \r\ninvalid: bar' + req.params.foo }); + break; +// {/fact} + + case 1: + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.writeHead(200, { test: req.params.foo + 'foo \ninvalid: bar' }); + break; + case 2: + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.writeHead(200, { test: 'foo \rinvalid: bar' + req.params.foo + 'asdadasd', foo: bar }); + break; +// {/fact} + + case 3: + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.writeHead(200, { test: bla + 'foo \n\n\ninvalid: bar' + req.params.foo }); + break; +// {/fact} + + case 5: + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.writeHead(200, { test: bla + 'foo \n\n\ninvalid: bar' + req.body.foo('asd') }); + break; +// {/fact} + + case 4: + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.writeHead(200, { test: req.params.foo }); + server.close(); + break; +// {/fact} + + default: + assert(false); + } + res.end('Hi mars!'); +}); +server.listen(common.PORT); + +var express = require('express'); +var app = express(); +app.get('/', function (req: { foo: string; query: { (arg0: string): string; (arg0: string): string;[x: string]: string; foo: any; }; }, res: { writeHead: (arg0: number, arg1: { test?: string; tast?: any; }) => void; set: (arg0: string, arg1: string | undefined) => void; }) { + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.writeHead(200, { test: 'foo \r\ninvalid: bar' + req.body.foo }); +// {/fact} + + + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.set('Content-Type', req.query.foo); +// {/fact} + + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.set('foo', 'asdad' + req.query.foo); +// {/fact} + + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.set(req.query.foo, 'asdadad'); +// {/fact} + + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.set('asda' + req.query.foo, 'asdadad'); +// {/fact} + + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.set('asda' + req.query["foo"], 'asdadad'); +// {/fact} + + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.set('asda' + req.query("foo"), 'asdadad'); +// {/fact} + + // {fact rule=neutralization-of-http@v1.0 defects=1} + // ruleid:generic_header_injection + res.set({ + 'Content-Type': 'text/plain', + 'Content-Length': req.query.foo, + 'ETag': '12345' + }) + //do not detect + res.writeHead(200, { tast: ddd }) + res.set(ffff) +}); +// {/fact} + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_injection.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_injection.yaml new file mode 100644 index 0000000..0e64f4f --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_injection.yaml @@ -0,0 +1,55 @@ +rules: + - id: generic_header_injection + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $INP = $REQ.$QUERY; + ... + $RES.set(..., <... $INP ...>, ...); + - pattern: | + $INP = $REQ.$QUERY.$VAR; + ... + $RES.set(..., <... $INP ...>, ...); + - pattern: | + $INP = $REQ.$VAR; + ... + $RES.set(..., { $X: <... $INP ...>}, ...); + - pattern: | + $INP = $REQ.$QUERY.$FOO; + ... + $RES.set(..., { $X: <... $INP ...>}, ...); + - pattern: | + $INP = $REQ.$VAR; + ... + $RES.writeHead(..., { $X: <... $INP ...> }, ...); + - pattern: | + $INP = $REQ.$QUERY.$FOO; + ... + $RES.writeHead(..., { $X: <... $INP ...> }, ...); + - pattern: | + $RES.set(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $RES.set(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $RES.set(..., { $X: <... $REQ.$VAR ...>}, ...) + - pattern: | + $RES.set(..., { $X: <... $REQ.$QUERY.$FOO ...>}, ...); + - pattern: | + $RES.writeHead(..., { $X: <... $REQ.$VAR ...> }, ...); + - pattern: | + $RES.writeHead(..., { $X: <... $REQ.$QUERY.$FOO ...> }, ...); + message: >- + Untrusted user input in response header will result in HTTP Header + Injection or Response Splitting Attacks. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: 'CWE-644: Improper Neutralization of HTTP Headers for Scripting Syntax' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_xss_protection.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_xss_protection.ts new file mode 100644 index 0000000..5ab972c --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_xss_protection.ts @@ -0,0 +1,80 @@ +import express from 'express'; +import lusca from 'lusca'; + +const app = express(); +// {fact rule=protection-mechanism-failure@v1.0 defects=1} +// ruleid:header_xss_lusca +app.use(lusca({ + csrf: true, + csp: { policy: "referrer no-referrer" }, + xframe: 'SAMEORIGIN', + p3p: 'ABCDEF', + hsts: { maxAge: 31536000, includeSubDomains: true, preload: true }, + xssProtection: false, + nosniff: true, + referrerPolicy: 'same-origin' +})); +// {/fact} + +// {fact rule=protection-mechanism-failure@v1.0 defects=1} + +app.use(lusca.csrf()); +app.use(lusca.csp({ policy: [{ "img-src": "'self' http:" }, "block-all-mixed-content"], reportOnly: false })); +app.use(lusca.xframe('SAMEORIGIN')); +app.use(lusca.p3p('ABCDEF')); +app.use(lusca.hsts({ maxAge: 31536000 })); +// ruleid:header_xss_lusca +app.use(lusca.xssProtection(false)); +app.use(lusca.nosniff()); +app.use(lusca.referrerPolicy('same-origin')); + +// {/fact} + +app.get('/', function (req, res) { + +// Just a variable, which is used later in another case. + var x = 0; + +// {fact rule=protection-mechanism-failure@v1.0 defects=1} + // ruleid:header_xss_generic + res.writeHead(200, { 'x-xss-protection': 0 }); +// {/fact} + +// {fact rule=protection-mechanism-failure@v1.0 defects=1} + + // ruleid:header_xss_generic + res.set('x-xss-protection', 0); +// {/fact} + +// The case should be compliant and semgrep comments so. Made defect equals 0. +// {fact rule=protection-mechanism-failure@v1.0 defects=0} + //do not match + res.set('x-xss-protection', 1); +// {/fact} + +// {fact rule=protection-mechanism-failure@v1.0 defects=1} + // ruleid:header_xss_generic + res.set('X-XSS-Protection', 0); +// {/fact} + +// {fact rule=protection-mechanism-failure@v1.0 defects=1} + //sgrep bug - https://github.com/returntocorp/sgrep/issues/512 + // ruleid:header_xss_generic + res.set({ + 'Content-Length': req.query.foo, + 'x-xss-protection': 0, + 'ETag': '12345' + }) +// {/fact} + +// {fact rule=protection-mechanism-failure@v1.0 defects=1} + //sgrep bug - https://github.com/returntocorp/sgrep/issues/512 + // ruleid:header_xss_generic + res.writeHead(200, { 'x-xss-protection': 0 }) + res.set('X-XSS-Protection', x); + + // do not detect + res.set(ffff) +}); +// {/fact} + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_xss_protection.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_xss_protection.yaml new file mode 100644 index 0000000..3be3c29 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/header_xss_protection.yaml @@ -0,0 +1,68 @@ +rules: + - id: header_xss_lusca + patterns: + - pattern-inside: | + $X = require('lusca'); + ... + - pattern-not: | + $X.use(helmet()) + - pattern-either: + - pattern: | + $X.xssProtection(false) + - pattern: | + $X({ xssProtection: false}) + message: >- + X-XSS-Protection header is set to 0. This will disable the browser's XSS + Filter. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: 'CWE-693: Protection Mechanism Failure' + - id: header_xss_generic + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $RES.header("=~/[X-XSS-Protection|x-xss-protection]/", 0, ...) + - pattern: | + $RES.set("=~/[X-XSS-Protection|x-xss-protection]/", 0, ...) + - pattern: > + $RES.set(..., { "=~/[X-XSS-Protection|x-xss-protection]/" : 0 }, + ...) + - pattern: > + $RES.writeHead(..., {"=~/[X-XSS-Protection|x-xss-protection]/": 0 + }, ...); + - pattern: | + $VAL = 0; + ... + $RES.header("=~/[X-XSS-Protection|x-xss-protection]/", $VAL, ...); + - pattern: | + $VAL = 0; + ... + $RES.set("=~/[X-XSS-Protection|x-xss-protection]/", $VAL, ...); + - pattern: > + $VAL = 0; + ... + $RES.set(..., { "=~/[X-XSS-Protection|x-xss-protection]/" : $VAL + }, ...); + - pattern: > + $VAL = 0; + ... + $RES.writeHead(..., {"=~/[X-XSS-Protection|x-xss-protection]/": + $VAL }, ...); + message: >- + X-XSS-Protection header is set to 0. This will disable the browser's XSS + Filter. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: 'CWE-693: Protection Mechanism Failure' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/host_header_injection.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/host_header_injection.ts new file mode 100644 index 0000000..ab21f7f --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/host_header_injection.ts @@ -0,0 +1,86 @@ +var express = require('express'); +var app = express(); + +// https://www.acunetix.com/blog/articles/automated-detection-of-host-header-attacks/ +app.get('/', function (req: { (arg0: string): string; (arg0: string): string;[x: string]: string; host: any; foo: any; }, res: any) { + + //semgrep string lateral support is pending + var foo = { + text: `reset url: https://${req.host}/password_reset/${token}` + }; + + //do not match + var x = 'https://' + foo + // do not match + var x = "https://" + req.foo + "/reset" + foo; + // do not match + var x = "https://" + z + "/reset"; + + +// {fact rule=improper-input-validation@v1.0 defects=1} + // ruleid:host_header_injection + var url = 'http://' + req.host; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + // ruleid:host_header_injection + var reset = 'https://' + req.host + '/password_reset'; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + // ruleid:host_header_injection + var pass = "https://" + req.host + "/reset"; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + + // ruleid:host_header_injection + var z = req.host; + var pass = "https://" + z + "/reset"; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + + // ruleid:host_header_injection + var reset_url = "Reset password: Reset"; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + // ruleid:host_header_injection + var foo = { + text: 'password: https://' + req.host + '/token/', + token: 'f2131ASDSADASoo', + }; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + + // ruleid:host_header_injection + var foo = { + text: 'reset password: https://' + req['host'] + '/token/', + token: 'f2131ASDSADASoo', + }; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + + // ruleid:host_header_injection + let x = "https://" + req['host'] + "/reset" + foo; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + // ruleid:host_header_injection + x = "https://" + req("host") + "/reset" + foo + 'barr' + foo2; +// {/fact} + + // {fact rule=improper-input-validation@v1.0 defects=1} + + // ruleid:host_header_injection + var foo = { + text: 'reset password: https://' + req.host + '/resettoken/' + foo, + token: 'f2131ASDSADASoo', + }; +// {/fact} + + +}); diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/host_header_injection.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/host_header_injection.yaml new file mode 100644 index 0000000..3afde67 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/host_header_injection.yaml @@ -0,0 +1,55 @@ +rules: + - id: host_header_injection + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $X = <... "=~/.*http[s]*:///" + $REQ.host ...>; + - pattern: | + $X = <... "=~/.*http[s]*:///" + $REQ["host"] ...>; + - pattern: | + $X = <... "=~/.*http[s]*:///" + $REQ("host") ...>; + - pattern: | + $X = { $Y: <... "=~/.*http[s]*:///" + $REQ.host ...>}; + - pattern: | + $X = { $Y: <... "=~/.*http[s]*:///" + $REQ["host"] ...>}; + - pattern: | + $X = { $Y: <... "=~/.*http[s]*:///" + $REQ("host") ...>}; + - pattern: | + $Z = $REQ.host; + ... + $X = <... "=~/.*http[s]*:///" + $Z ...>; + - pattern: | + $Z = $REQ["host"]; + ... + $X = <... "=~/.*http[s]*:///" + $Z ...>; + - pattern: | + $Z = $REQ("host"); + ... + $X = <... "=~/.*http[s]*:///" + $Z ...>; + - pattern: | + $Z = $REQ.host; + ... + $X = { $Y: <... "=~/.*http[s]*:///" + $REQ.host ...>}; + - pattern: | + $Z = $REQ["host"]; + ... + $X = { $Y: <... "=~/.*http[s]*:///" + $Z ...>}; + - pattern: | + $Z = $REQ("host"); + ... + $X = { $Y: <... "=~/.*http[s]*:///" + $REQ("host") ...>}; + message: >- + Using untrusted Host header for generating dynamic URLs can result in web + cache and or password reset poisoning. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: 'CWE-20: Improper Input Validation' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/jwt_none_algorithm.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/jwt_none_algorithm.ts new file mode 100644 index 0000000..af8224f --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/jwt_none_algorithm.ts @@ -0,0 +1,20 @@ +// {fact rule=insecure-cryptography@v1.0 defects=1} +// ruleid:node_jwt_none_algorithm +import jose from "jose"; +const { JWK, JWT } = jose; +const token = JWT.verify('token-here', JWK.None); +// {/fact} + + +// {fact rule=insecure-cryptography@v1.0 defects=1} +function verifyJwt() { + // ruleid:node_jwt_none_algorithm + let jwt = require("jsonwebtoken"); + let secret = 'some-secret'; + jwt.verify('token-here', secret, { algorithms: ['RS256', 'none'] }, function (err, payload) { + console.log(payload); + }); +} +// {/fact} + + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/jwt_none_algorithm.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/jwt_none_algorithm.yaml new file mode 100644 index 0000000..4b0b7db --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/jwt_none_algorithm.yaml @@ -0,0 +1,45 @@ +# Rule from : https://github.com/returntocorp/semgrep-rules/blob/develop/javascript/jwt-none-alg/jwt-none-alg.yaml +# https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/#Meet-the--None--Algorithm +rules: + - id: node_jwt_none_algorithm + patterns: + - pattern-either: + - pattern: | + $JWT = require("jsonwebtoken"); + ... + $T = $JWT.verify($P, $X, {algorithms:[...,'none',...]},...); + - pattern: | + $JWT = require("jsonwebtoken"); + ... + $T = $JWT.verify($P, $X, {algorithms:[...,'none',...]},...); + - pattern: | + $JWT = require("jsonwebtoken"); + ... + $JWT.verify($P, $X, {algorithms:[...,'none',...]},...); + - pattern: | + $JOSE = require("jose"); + ... + var { JWK, JWT } = $JOSE; + ... + $T = JWT.verify($P, JWK.None,...); + - pattern: | + $JOSE = require("jose"); + ... + var { JWK, JWT } = $JOSE; + ... + $T = JWT.verify($P, JWK.None,...); + - pattern: | + $JOSE = require("jose"); + ... + var { JWK, JWT } = $JOSE; + ... + JWT.verify($P, JWK.None,...); + message: >- + Algorithm is set to none for JWT token. This can nullify the integrity of + JWT signature. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A9: Using Components with Known Vulnerabilities' + cwe: 'CWE-327: Use of a Broken or Risky Cryptographic Algorithm' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/layer7_object_dos.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/layer7_object_dos.ts new file mode 100644 index 0000000..7de20dd --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/layer7_object_dos.ts @@ -0,0 +1,34 @@ +import express from 'express'; +const router = express.Router() + +// {fact rule=resource-leak@v1.0 defects=1} +router.post("/list-users", (req: { body: { users: any; }; }, res: any) => { + var obj = req.body.users; + var someArr = []; + + // Potential DoS if obj.length is large. + // ruleid:layer7_object_dos + for (var i = 0; i < obj.length; i++) { + someArr.push(obj[i]); + } + +}); +// {/fact} + + + +module.exports = router + +// {fact rule=resource-leak@v1.0 defects=1} +app.post("/foo", (req: { body: any; }, res: any) => { + var obj = req.body; + + var ret = []; + + // Potential DoS if obj.length is large. + // ruleid:layer7_object_dos + for (var i = 0; i < obj.length; i++) { + ret.push(obj[i]); + } +}); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/layer7_object_dos.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/layer7_object_dos.yaml new file mode 100644 index 0000000..d077a6e --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/layer7_object_dos.yaml @@ -0,0 +1,29 @@ +rules: + - id: layer7_object_dos + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern-inside: | + $OBJ = $REQ.body; + ... + - pattern-inside: | + $OBJ = $REQ.body.$FOO; + ... + - pattern-either: + - pattern-inside: | + for(...){...}; + - pattern: | + $OBJ.length; + message: Layer7 Denial of Service. Looping over user controlled objects can result in DoS. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: >- + CWE-400: Uncontrolled Resource Consumption \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/logic_bypass.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/logic_bypass.yaml new file mode 100644 index 0000000..cc6ff5b --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/logic_bypass.yaml @@ -0,0 +1,55 @@ +rules: + - id: node_logic_bypass + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $REQ.$FOO.$BAR !== $REQ.$ZOO.$ZAR + - pattern: | + $REQ.$FOO.$BAR === $REQ.$ZOO.$ZAR + - pattern: | + $REQ.$FOO.$BAR >= $REQ.$ZOO.$ZAR + - pattern: | + $REQ.$FOO.$BAR <= $REQ.$ZOO.$ZAR + - pattern: | + $REQ.$FOO.$BAR < $REQ.$ZOO.$ZAR + - pattern: | + $REQ.$FOO.$BAR > $REQ.$ZOO.$ZAR + - pattern: | + $REQ.$FOO['...'] !== $REQ.$ZOO['...'] + - pattern: | + $REQ.$FOO['...'] === $REQ.$ZOO['...'] + - pattern: | + $REQ.$FOO['...'] >= $REQ.$ZOO['...'] + - pattern: | + $REQ.$FOO['...'] <= $REQ.$ZOO['...'] + - pattern: | + $REQ.$FOO['...'] < $REQ.$ZOO['...'] + - pattern: | + $REQ.$FOO['...'] > $REQ.$ZOO['...'] + - pattern: | + $REQ.$FOO('...') !== $REQ.$ZOO('...') + - pattern: | + $REQ.$FOO('...') === $REQ.$ZOO('...') + - pattern: | + $REQ.$FOO('...') >= $REQ.$ZOO('...') + - pattern: | + $REQ.$FOO('...') <= $REQ.$ZOO('...') + - pattern: | + $REQ.$FOO('...') < $REQ.$ZOO('...') + - pattern: | + $REQ.$FOO('...') > $REQ.$ZOO('...') + message: >- + User controlled data is used for application business logic decision + making. This expose protected data or functionality. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A5: Broken Access Control' + cwe: 'CWE-807: Reliance on Untrusted Inputs in a Security Decision' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/logic_user_controlled_checks.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/logic_user_controlled_checks.ts new file mode 100644 index 0000000..ae8224c --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/logic_user_controlled_checks.ts @@ -0,0 +1,13 @@ +var express = require('express'); +var app = express(); +app.get('/view/:id', function (req: { cookies: { [x: string]: any; }; params: { [x: string]: any; }; }, res: any) { + +// {fact rule=untrusted-data-in-decision@v1.0 defects=1} + // ruleid:node_logic_bypass + if (req.cookies["user"] === req.params["id"]) { + showProfile(); + } + +}); +// {/fact} + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/missing_good_controls.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/missing_good_controls.ts new file mode 100644 index 0000000..c8d13c0 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/missing_good_controls.ts @@ -0,0 +1,35 @@ +app.post('/entry', (req: { body: { message: any; }; }, res: { send: (arg0: string) => void; }) => { + console.log(`Message received: ${req.body.message}`); + res.send(`CSRF token not used`); +}); + +app.post('/auth', function (request: { body: { username: any; password: any; }; session: { loggedin: boolean; username: any; }; }, response: { redirect: (arg0: string) => void; send: (arg0: string) => void; end: () => void; }) { + var username = request.body.username; + var password = request.body.password; + if (username && password) { + connection.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function (error: any, results: string | any[], fields: any) { + if (results.length > 0) { + request.session.loggedin = true; + request.session.username = username; + response.redirect('/home'); + } else { + response.send('Incorrect Username and/or Password!'); + } + response.end(); + }); + } else { + response.send('Please enter Username and Password!'); + response.end(); + } +}); + +// missing helmet +const helmet = require('helmet') +const xssFilter = require('x-xss-protection') +const noSniff = require('dont-sniff-mimetype') +const hsts = require('hsts') +const frameguard = require('frameguard') +const permittedCrossDomainPolicies = require('helmet-crossdomain') + +app.use(helmet.dnsPrefetchControl({ allow: true })) +app.use(dnsPrefetchControl({ allow: true })) \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/nosql_injection.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/nosql_injection.ts new file mode 100644 index 0000000..fdd6c43 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/nosql_injection.ts @@ -0,0 +1,91 @@ +var MongoClient = require('mongodb').MongoClient; +// mongo js injection https://lockmedown.com/securing-node-js-mongodb-security-injection-attacks/ +// {fact rule=nosql-injection@v1.0 defects=1} +timelineRouter.route("/api/timeline") + .get(async function (req: { foo: { bar: any; }; query: { end: any; }; }, res: { json: (arg0: { timelineItems: any; }) => any; status: (arg0: number) => { (): any; new(): any; send: { (arg0: string): void; new(): any; }; }; }) { + try { + var foo = req.foo.bar; + const startDate = "01/01/2000"; + // ruleid:node_nosqli_js_injection + const endDate = req.query.end; + const query = { $where: "this.hidden == false" }; + + if (startDate && endDate) { + query["$where"] = "this.start >= new Date('" + startDate + "') && " + + "this.end <= new Date('" + endDate + "') &&" + + "this.hidden == false;"; + } + + const TimelineItem = await getTimelineItemModel(); + const timelineItems = await TimelineItem.find(query); + console.log(colors.yellow(`# of Timeline Items retrieved: ${timelineItems.length}`)); + return res.json({ timelineItems: timelineItems }); + + } catch (error) { + res.status(500).send("There was an error retrieving timeline items. Please try again later"); + } + }); +// {/fact} + +// {fact rule=nosql-injection@v1.0 defects=1} +// https://nullsweep.com/a-nosql-injection-primer-with-mongo/ +// ruleid:node_nosqli_js_injection +let username = req.query.username; +var query = { $where: `this.username == '${username}'` } +User.find(query, function (err: any, users: any) { + if (err) { + // Handle errors + } else { + res.render('userlookup', { title: 'User Lookup', users: users }); + } +}); +// {/fact} + +// {fact rule=nosql-injection@v1.0 defects=1} +app.post('/foo', function (req: { body: { email: any; }; }, res: { send: (arg0: string) => void; }) { +// ruleid:node_nosqli_js_injection + var query = {}; + query['$where'] = `this.email == '${req.body.email}'`; + User.find(query, function (err: any, data: any) { + if (err) { + res.send(err); + } else if (data) { + res.send('User Login Successful'); + } else { + res.send('Wrong Username Password Combination'); + } + }) +}); +// {/fact} + +// {fact rule=nosql-injection@v1.0 defects=1} +app.post('/smth', function (req: { body: { email: any; }; }, res: { send: (arg0: string) => void; }) { +// ruleid:node_nosqli_injection + var query = {}; + query['email'] = req.body.email; + User.findOne(query, function (err: any, data: any) { + if (err) { + res.send(err); + } else if (data) { + res.send('User Login Successful'); + } else { + res.send('Wrong Username Password Combination'); + } + }) +}); +// {/fact} + +// {fact rule=nosql-injection@v1.0 defects=1} +app.post('/login', function (req: { body: { email: any; password: any; }; }, res: { send: (arg0: string) => void; }) { +// ruleid:node_nosqli_injection + User.findOne({ 'email': req.body.email, 'password': req.body.password }, function (err: any, data: any) { + if (err) { + res.send(err); + } else if (data) { + res.send('User Login Successful'); + } else { + res.send('Wrong Username Password Combination'); + } + }) +}); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/nosql_injection.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/nosql_injection.yaml new file mode 100644 index 0000000..450b4ec --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/nosql_injection.yaml @@ -0,0 +1,167 @@ +rules: +- id: node_nosqli_js_injection + patterns: + - pattern-either: + - pattern: | + $OBJ.$FUNC({$where: <... $REQ.$FOO.$BAR ...>}, ...); + - pattern: | + $OBJ.$FUNC({$where: <... $REQ.$QUERY ...>}, ...); + - pattern: | + $NSQL = <... $REQ.$QUERY.$...>; + ... + $OBJ.$FUNC({$where: <... $NSQL ...>}, ...); + - pattern: | + $NSQL = <... $REQ.$QUERY ...>; + ... + $OBJ.$FUNC({$where: <... $NSQL ...>}, ...); + - pattern: | + $INP = $REQ.$FOO.$BAR; + ... + $QRY = {$where: <... $INP ...>}; + ... + $OBJ.$FUNC(<... $QRY ...>, ...); + - pattern: | + $INP = $REQ.$FOO; + ... + $QRY = {$where: <... $INP ...>}; + ... + $OBJ.$FUNC(<... $QRY ...>, ...); + - pattern: | + $QRY = {}; + ... + $QRY["$where"] = <... $REQ.$FOO ...>; + ... + $OBJ.$FUNC(<... $QRY ...>, ...); + - pattern: | + $QRY = {}; + ... + $QRY["$where"] = <... $REQ.$FOO.$BAR ...>; + ... + $OBJ.$FUNC(<... $QRY ...>, ...); + - pattern: | + $INP = $REQ.$FOO; + ... + $QRY = {}; + ... + $QRY["$where"] = <... $INP ...>; + ... + $OBJ.$FUNC(<... $QRY ...>, ...); + - pattern: | + $INP = $REQ.$FOO.$BAR; + ... + $QRY = {}; + ... + $QRY["$where"] = <... $INP ...>; + ... + $OBJ.$FUNC(<... $QRY ...>, ...); + - pattern: | + $QRY = {}; + ... + $INP = $REQ.$FOO; + ... + $QRY["$where"] = <... $INP ...>; + ... + $OBJ.$FUNC(<... $QRY ...>, ...); + - pattern: | + $QRY = {}; + ... + $INP = $REQ.$FOO.$BAR; + ... + $QRY["$where"] = <... $INP ...>; + ... + $OBJ.$FUNC(<... $QRY ...>, ...); + message: >- + Untrusted user input in MongoDB $where operator can result in NoSQL + JavaScript Injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: 'CWE-943: Improper Neutralization of Special Elements in Data Query Logic' +- id: node_nosqli_injection + patterns: + - pattern-either: + - pattern: | + $OBJ.findOne({$KEY : <... $REQ.$FOO.$BAR ...> }, ...); + - pattern: | + $OBJ.findOne({$KEY: <... $REQ.$FOO ...> }, ...); + - pattern: | + $INP = <... $REQ.$FOO.$BAR ...>; + ... + $OBJ.findOne({$KEY : <... $INP ...> }, ...); + - pattern: | + $INP = <... $REQ.$FOO ...>; + ... + $OBJ.findOne({$KEY: <... $INP ...> }, ...); + - pattern: | + $QUERY = {$KEY: <... $REQ.$FOO.$BAR ...>}; + ... + $OBJ.findOne($QUERY, ...); + - pattern: | + $QUERY = {$KEY: <... $REQ.$FOO ...>}; + ... + $OBJ.findOne($QUERY, ...); + - pattern: | + $INP = <... $REQ.$FOO.$BAR ...>; + ... + $QUERY = {$KEY : <... $INP ...> }; + ... + $OBJ.findOne(<... $QUERY ...>, ...); + - pattern: | + $INP = <... $REQ.$FOO ...>; + ... + $QUERY = {$KEY : <... $INP ...> }; + ... + $OBJ.findOne(<... $QUERY ...>, ...); + - pattern: | + $QUERY = {}; + ... + $QUERY[$KEY] = <... $REQ.$FOO.$BAR ...>; + ... + $OBJ.findOne($QUERY, ...); + - pattern: | + $QUERY = {}; + ... + $QUERY[$KEY] = <... $REQ.$FOO ...>; + ... + $OBJ.findOne($QUERY, ...); + - pattern: | + $INP = <... $REQ.$FOO.$BAR ...>; + ... + $QUERY = {}; + ... + $QUERY[$KEY] = <... $INP ...>; + ... + $OBJ.findOne(<... $QUERY ...>, ...); + - pattern: | + $INP = <... $REQ.$FOO ...>; + ... + $QUERY = {}; + ... + $QUERY[$KEY] = <... $INP ...>; + ... + $OBJ.findOne(<... $QUERY ...>, ...); + - pattern: | + $QUERY = {}; + ... + $INP = <... $REQ.$FOO.$BAR ...>; + ... + $QUERY[$KEY] = <... $INP ...>; + ... + $OBJ.findOne(<... $QUERY ...>, ...); + - pattern: | + $QUERY = {}; + ... + $INP = <... $REQ.$FOO ...>; + ... + $QUERY[$KEY] = <... $INP ...>; + ... + $OBJ.findOne(<... $QUERY ...>, ...); + message: Untrusted user input in findOne() function can result in NoSQL Injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: 'CWE-943: Improper Neutralization of Special Elements in Data Query Logic' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/open_redirect.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/open_redirect.ts new file mode 100644 index 0000000..1632b86 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/open_redirect.ts @@ -0,0 +1,191 @@ +import express from 'express'; +const router = express.Router() + +router.use((req: { method: string; session: { data: any; }; }, res: any, next: () => void) => { + if (req.method === 'POST') { + console.log(JSON.stringify(req.session.data, null, 2)) + } + next() +}) + +router.post('/sprint18b/frequency', (req: any, res: { redirect: (arg0: string) => void; }) => { + res.redirect('/sprint18b/payment') //GOOD +}); + +var express = require('express'); + +var app = express(); +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/some/path', function (req: { param: (arg0: string) => any; }, res: { redirect: (arg0: number, arg1: any) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect + res.redirect(302, req.param("target")); +}); +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/some/path1', function (req: { param: any; }, res: { redirect: (arg0: number, arg1: any) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect + res.redirect(300, req.param); +}); +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/some/path2', function (req: { param: { [x: string]: any; }; }, res: { redirect: (arg0: any) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect + res.redirect(req.param["target"]); +}); +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/some/path3', function (req: { body: { url: any; }; }, res: { redirect: (arg0: any) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect + res.redirect(req.body.url); +}); +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/some/path4', function (req: { param: (arg0: string) => string; }, res: { redirect: (arg0: string) => void; }) { + // BAD subdomain control + // ruleid:express_open_redirect + res.redirect("sdcssf" + req.param("target")); +}); +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/some/path5', function (req: { param: (arg0: string) => string; }, res: { redirect: (arg0: string) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect + res.redirect(req.param("target") + "/asdad"); +}); +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} +app.all(function (req: { param: { [x: string]: any; }; }, res: { header: (arg0: string, arg1: any) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect2 + res.header("Location", req.param["target"]); +}); +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} + +app.all(function (req: { param: (arg0: string) => any; }, res: { header: (arg0: string, arg1: any) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect2 + res.header('Location', req.param("foo")); +}); +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} + +app.all(function (req: { foo: string; }, res: { writeHead: (arg0: number, arg1: { location: string; foo: any; }) => void; }) { + // ruleid:express_open_redirect2 + res.writeHead(200, { location: 'foo \rinvalid: bar' + req.params.foo + 'asdadasd', foo: bar }); +}); + +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} +app.all(function (req: { foo: any; }, res: { writeHead: (arg0: number, arg1: { location: any; }) => void; }) { + // ruleid:express_open_redirect2 + res.writeHead(200, { 'location': req.params.foo }); +}); +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} +app.all(function (req: { param: (arg0: string) => any; }, res: { header: (arg0: string, arg1: any) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect2 + res.header('location', req.param("bar")); +}); +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/some/path', function (req: { param: (arg0: string) => any; }, res: { redirect: (arg0: any) => void; }) { + // ruleid:express_open_redirect + var target = req.param("target"); + // BAD: sanitization doesn't apply here + res.redirect(target); +}); +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/foo', function (req: { param: (arg0: string) => string; }, res: { redirect: (arg0: any) => void; }) { + // BAD: may be a global redirection + // ruleid:express_open_redirect + res.redirect((req.param('action') && req.param('action') != "") ? req.param('action') : "/google_contacts") +}); +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/yet/another/path', function (req: { param: (arg0: string) => any; }, res: { redirect: (arg0: string) => void; }) { + // BAD: a request parameter is incorporated without validation into a URL redirect + // ruleid:express_open_redirect + res.redirect(`${req.param("target")}/foo`); +}); +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/array/join', function (req: { query: { page: any; section: any; }; }, res: { redirect: (arg0: string) => void; }) { + // BAD: request input becomes before query string + // ruleid:express_open_redirect + res.redirect([req.query.page, '?section=', req.query.section].join('')); +}); +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/call', function (req: { query: { nextUrl: any; }; }, res: any) { + sendUserToUrl(res, req.query.nextUrl); +}); + +function sendUserToUrl(res: { redrect: (arg0: any) => void; }, nextUrl: any) { + // BAD: value comes from query parameter + res.redirect(nextUrl); +} +// {/fact} + + +// {fact rule=open-redirect@v1.0 defects=1} +app.get('/redirect/:user', function (req: { params: { user: string; }; }, res: { redirect: (arg0: string) => void; }) { + + // ruleid:express_open_redirect + res.redirect('/' + req.params.user); // BAD - could go to //evil.com +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} + // ruleid:express_open_redirect + res.redirect('//' + req.params.user); // BAD - could go to //evil.com +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} + // ruleid:express_open_redirect + res.redirect('u' + req.params.user); // BAD - could go to u.evil.com +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} + // ruleid:express_open_redirect + res.redirect('Fan999' + req.params.user); // BAD - could go to Fan999.evil.com +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=1} + // ruleid:express_open_redirect + res.redirect('/' + ('/u' + req.params.user)); // BAD - could go to //u.evil.com, +// {/fact} + +// {fact rule=open-redirect@v1.0 defects=0} + //do not trigger + res.redirect('/' + foo) +}); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/open_redirect.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/open_redirect.yaml new file mode 100644 index 0000000..efc83d1 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/open_redirect.yaml @@ -0,0 +1,83 @@ +rules: + - id: express_open_redirect + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $X.redirect(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $X.redirect(..., <... $REQ.$QUERY.$FOO ...>, ...) + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $X.redirect(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$FOO ...>; + ... + $X.redirect(..., <... $INP ...>, ...); + message: >- + Untrusted user input in redirect() can result in Open Redirect + vulnerability. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-601: URL Redirection to Untrusted Site ('Open Redirect') + - id: express_open_redirect2 + patterns: + - pattern-inside: | + $APP.$METHOD(..., function $FUNC($REQ, $RES) { ... }) + - pattern-either: + - pattern: | + $RES.header(..., "=~/[Ll]+ocation/", <... $REQ.$VAR ...>, ...) + - pattern: | + $RES.header(..., "=~/[Ll]+ocation/", <... $REQ.$VAR.$VARR ...>, ...) + - pattern: | + $RES.writeHead(..., "=~/[Ll]+ocation/", <... $REQ.$VAR ...>, ...) + - pattern: | + $RES.writeHead(..., "=~/[Ll]+ocation/", <... $REQ.$VAR.$VARR ...>, ...) + - pattern: | + $RES.writeHead(..., {"=~/[Ll]+ocation/": <... $REQ.$VAR ...> }, ...) + - pattern: | + $RES.writeHead(..., {"=~/[Ll]+ocation/": <... $REQ.$VAR.$VARR ...> }, ...) + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $RES.header(..., "=~/[Ll]+ocation/", <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$VARR ...>; + ... + $RES.header(..., "=~/[Ll]+ocation/", <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $RES.writeHead(..., "=~/[Ll]+ocation/", <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$VARR ...>; + ... + $RES.writeHead(..., "=~/[Ll]+ocation/", <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $RES.writeHead(..., {"=~/[Ll]+ocation/": <... $INP ...> }, ...); + - pattern: | + $INP = <... $REQ.$VAR.$VARR ...>; + ... + $RES.writeHead(..., {"=~/[Ll]+ocation/": <... $INP ...> }, ...); + message: >- + Untrusted user input in response header('Location') can result in Open + Redirect vulnerability. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-601: URL Redirection to Untrusted Site ('Open Redirect') diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/path_traversal.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/path_traversal.ts new file mode 100644 index 0000000..751290f --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/path_traversal.ts @@ -0,0 +1,60 @@ +var http = require('http'), + fileSystem = require('fs'), + path = require('path'); + +var config = require('../config'); +var Promise = require('bluebird'); +Promise.promisifyAll(fileSystem); + +var express = require('express'); +var app = express(); +// {fact rule=path-traversal@v1.0 defects=1} + +app.get('/', function (req: { query: { load: string; foo: any; nar: any; y: any; }; }, res: any) { + // ruleid:generic_path_traversal + var filePath = path.join(__dirname, '/' + req.query.load); + var readStream = fileSystem.createReadStream(filePath); +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} + + // ruleid:generic_path_traversal + fileSystem.readFile(req.query.foo); +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} + + // ruleid:generic_path_traversal + console.log(fileSystem.readFileSync(req.query.nar, 'utf8')); +// {/fact} + +// {fact rule=path-traversal@v1.0 defects=1} + + // ruleid:generic_path_traversal + var foo = req.query.y; + fileSystem.readFile(foo); + fileSystem.readFile(foo + "bar"); + readStream.pipe(res); +}); +// {/fact} + + +// {fact rule=path-traversal@v1.0 defects=1} + +app.get('/foo', function (req: { query: { date: any; }; }, res: { download: (arg0: string, arg1: string) => void; }) { + // ruleid:generic_path_traversal + var date = req.query.date; + var fileName = config.dirName + '/' + date; + var downloadFileName = 'log_' + fileName + '.txt'; + + fs.readFileAsync(fileName) + .then(function(data: any) { + res.download(fileName, downloadFileName); + }) +}) + +app.listen(8888); +// do not match +fileSystem.readFile(ddd); +// {/fact} + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/path_traversal.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/path_traversal.yaml new file mode 100644 index 0000000..3b33c7a --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/path_traversal.yaml @@ -0,0 +1,128 @@ +rules: + - id: generic_path_traversal + patterns: + - pattern-either: + - pattern-inside: | + $HTTP = require('http'); + ... + - pattern-inside: | + $EXPRESS = require('express'); + ... + - pattern-inside: | + $KOA = require('koa'); + ... + - pattern-inside: | + $ELEC = require('electron'); + ... + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $X.createReadStream(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $X.createReadStream(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $X.readFile(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $X.readFile(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $X.readFileSync(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $X.readFileSync(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $X.readFileAsync(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $X.readFileAsync(..., <... $REQ.$QUERY ...>, ...) + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + $X.createReadStream(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $X.createReadStream(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + $X.readFile(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $X.readFile(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + $X.readFileSync(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $X.readFileSync(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + $X.readFileAsync(..., <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $X.readFileAsync(..., <... $INP ...>, ...); + - pattern: | + $Y = $REQ.$QUERY.$VAR; + ... + $INP = <... $Y ...>; + ... + $X.createReadStream(..., <... $INP ...>, ...); + - pattern: | + $Y = $REQ.$QUERY; + ... + $INP = <... $Y ...>; + ... + $X.createReadStream(..., <... $INP ...>, ...); + - pattern: | + $Y = $REQ.$QUERY.$VAR; + ... + $INP = <... $Y ...>; + ... + $X.readFile(..., <... $INP ...>, ...); + - pattern: | + $Y = $REQ.$QUERY; + ... + $INP = <... $Y ...>; + ... + $X.readFile(..., <... $INP ...>, ...); + - pattern: | + $Y = $REQ.$QUERY.$VAR; + ... + $INP = <... $Y ...>; + ... + $X.readFileSync(..., <... $INP ...>, ...); + - pattern: | + $Y = $REQ.$QUERY; + ... + $INP = <... $Y ...>; + ... + $X.readFileSync(..., <... $INP ...>, ...); + - pattern: | + $Y = $REQ.$QUERY.$VAR; + ... + $INP = <... $Y ...>; + ... + $X.readFileAsync(..., <... $INP ...>, ...); + - pattern: | + $Y = $REQ.$QUERY; + ... + $INP = <... $Y ...>; + ... + $X.readFileAsync(..., <... $INP ...>, ...); + message: >- + Untrusted user input in readFile()/readFileSync() can endup in Directory + Traversal Attacks. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A5: Broken Access Control' + cwe: 'CWE-23: Relative Path Traversal' \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_dos.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_dos.ts new file mode 100644 index 0000000..edc58ba --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_dos.ts @@ -0,0 +1,70 @@ +import express from 'express'; +const router = express.Router() + +// {fact rule=incorrect-expression@v1.0 defects=1} +router.get("/tstMe", (req: { params: { id: string; }; }, res: any) => { + var r = /([a-z]+)+$/; + // ruleid:regex_dos + let match = r.test(req.params.id); +}); +// {/fact} + + + +module.exports = router + +var http = require("http"); +var url = require("url"); +http.createServer(function (request: { url: any; foo: string; value: string; }, response: { end: () => void; }) { + + var myArray = /d(b+)d/g.exec('cdbbdbsbz'); + var emailExpression = /^([a-zA-Z0-9_\.\-])+\@/ + foo + /(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; + +// {fact rule=incorrect-expression@v1.0 defects=1} + // ruleid:regex_dos + var parsedUrl = url.parse(request.url, true); + console.timeEnd('benchmark'); + /^(([a-z])+.)+[A-Z]([a-z])+$/.test(parsedUrl.query); + + /^(([a-z])+.)+[A-Z]([a-z])+$/.test('a'.repeat(100)); + console.timeEnd('benchmark'); + let match = r.test(req.params.id); +// {/fact} + + // {fact rule=incorrect-expression@v1.0 defects=1} + // ruleid:regex_dos + /^(([a-z])+.)+[A-Z]([a-z])+$/.test(request.foo); + console.timeEnd('benchmark'); +// {/fact} + + // {fact rule=incorrect-expression@v1.0 defects=1} + // ruleid:regex_dos + var y = /^(([a-z])+.)+[A-Z]([a-z])+$/.test(request.foo['bar']); + console.timeEnd('benchmark'); + console.time('benchmark'); + var x = /^(([a-z])+.)+[A-Z]([a-z])+$/.test('a'.repeat(100)); + console.timeEnd('benchmark'); +// {/fact} + +// {fact rule=incorrect-expression@v1.0 defects=1} + // ruleid:regex_dos + var myArray = /d(b+)d/g.exec(request.foo.bar); + response.end(); + +// {/fact} + +// {fact rule=incorrect-expression@v1.0 defects=1} + // ruleid:regex_dos + var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/; + var OK = re.exec(request.value); + if (!OK) { + console.error(request.value + ' isn\'t a phone number with area code!'); + } else { + console.log('Thanks, your phone number is ' + OK[0]); + } + +}).listen(8888); + +// {/fact} + + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_dos.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_dos.yaml new file mode 100644 index 0000000..c8e6ee1 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_dos.yaml @@ -0,0 +1,67 @@ +rules: + - id: regex_dos + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $REGEX.test(<... $REQ ...>) + - pattern: | + $REGEX.test(<... $REQ.$QUERY ...>) + - pattern: | + $REGEX.test(<... $REQ.$BODY.$PARAM ...>) + - pattern: | + $INP = <... $REQ ...>; + ... + $REGEX.test(<... $INP ...>); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $REGEX.test(<... $INP ...>); + - pattern: | + $INP = <... $REQ.$BODY.$PARAM ...>; + ... + $REGEX.test(<... $INP ...>); + - pattern: | + /.../g.exec(<... $REQ ...>) + - pattern: | + /.../g.exec(<... $REQ.$QUERY ...>) + - pattern: | + /.../.exec(<... $REQ.$BODY.$PARAM ...>) + - pattern: | + $INP = <... $REQ ...>; + ... + /.../.exec(<... $INP ...>); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + /.../.exec(<... $INP ...>); + - pattern: | + $INP = <... $REQ.$BODY.$PARAM ...>; + ... + /.../.exec(<... $INP ...>); + - pattern: | + $RE = /.../; + ... + $RE.exec(<... $REQ ...>); + - pattern: | + $RE = /.../; + ... + $RE.exec(<... $REQ.$QUERY ...>); + - pattern: | + $RE = /.../; + ... + $RE.exec(<... $REQ.$BODY.$PARAM ...>); + message: >- + Ensure that the regex used to compare with user supplied input is safe + from regular expression denial of service. + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: 'CWE-185: Incorrect Regular Expression' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_injection.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_injection.yaml new file mode 100644 index 0000000..f970ab9 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_injection.yaml @@ -0,0 +1,67 @@ +rules: + - id: regex_injection_dos + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $INP = <... $REQ.$PARAM ...>; + ... + $RE = new RegExp(<... $INP ...>); + - pattern: | + $INP = <... $REQ.$PARAM.$BAR ...>; + ... + $RE = new RegExp(<... $INP ...>); + - pattern: | + new RegExp(<... $REQ.$PARAM ...>); + - pattern: | + new RegExp(<... $REQ.$PARAM.$BAR ...>); + - pattern: | + $INP = <... $REQ.$PARAM ...>; + ... + $RE = $STR.search(<... $INP ...>); + - pattern: | + $INP = <... $REQ.$PARAM.$FOO ...>; + ... + $RE = $STR.search(<... $INP ...>); + - pattern: | + $STR.search(<... $REQ.$PARAM ...>); + - pattern: | + $STR.search(<... $REQ.$PARAM.$BAR ...>); + - pattern: | + $INP = <... $REQ.$PARAM ...>; + ... + $RE = $STR.match(<... $INP ...>); + - pattern: | + $INP = <... $REQ.$PARAM.$FOO ...>; + ... + $RE = $STR.match(<... $INP ...>); + - pattern: | + $STR.match(<... $REQ.$PARAM ...>); + - pattern: | + $STR.match(<... $REQ.$PARAM.$BAR ...>); + - pattern: | + $INP = <... $REQ.$PARAM ...>; + ... + $RE = $STR.split(<... $INP ...>); + - pattern: | + $INP = <... $REQ.$PARAM.$FOO ...>; + ... + $RE = $STR.split(<... $INP ...>); + - pattern: | + $STR.split(<... $REQ.$PARAM ...>); + - pattern: | + $STR.split(<... $REQ.$PARAM.$BAR ...>); + message: >- + User controlled data in RegExp() can make the application vulnerable to + layer 7 DoS. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: 'CWE-400: Uncontrolled Resource Consumption' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_injection_dos.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_injection_dos.ts new file mode 100644 index 0000000..350fea1 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/regex_injection_dos.ts @@ -0,0 +1,12 @@ +var express = require('express'); +var app = express(); +// {fact rule=resource-leak@v1.0 defects=1} +app.get('/search', function (req: { param: (arg0: string) => any; }, res: any) { + // ruleid:regex_injection_dos + var key = req.param("key"); + // Regex created from user input + var re = new RegExp("\\b" + key); +}); +//do not detect this +var re = new RegExp("\\b" + key + "=(.*)\n"); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/security_electron.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/security_electron.ts new file mode 100644 index 0000000..f6e7385 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/security_electron.ts @@ -0,0 +1,87 @@ +import electron = require('electron'); +const BrowserWindow = electron.BrowserWindow; + +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_disable_websecurity +const mainWindow = new BrowserWindow({ + webPreferences: { + webSecurity: false + } +}) +// {/fact} + +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_disable_websecurity +const config = { + webPreferences: { + webSecurity: false + } +} +// {/fact} + +var newwin = new BrowserWindow(config) +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_allow_http +const mainWindow = new BrowserWindow({ + webPreferences: { + allowRunningInsecureContent: true + } +}) +// {/fact} + +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_disable_websecurity +var x = new BrowserWindow({ + webPreferences: { + webSecurity: false, + allowRunningInsecureContent: true + } +}) +// {/fact} + +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_blink_integration +const mainWindow = new BrowserWindow({ + webPreferences: { + enableBlinkFeatures: 'ExecCommandInJavaScript' + } +}) +// {/fact} + +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_allow_http +const mainWindow = new BrowserWindow({ + webPreferences: { + allowRunningInsecureContent: true + } +}) +// {/fact} + +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_nodejs_integration +const mainWindow = new BrowserWindow({ + webPreferences: { + nodeIntegration: true, + nodeIntegrationInWorker: true + } +}) +// {/fact} + +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_context_isolation +const mainWindow = new BrowserWindow({ + webPreferences: { + contextIsolation: false, + preload: path.join(app.getAppPath(), 'preload.js') + } +}) +// {/fact} + +// {fact rule=least-privilege-violation@v1.0 defects=1} +// ruleid:electron_experimental_features +const mainWindow = new BrowserWindow({ + webPreferences: { + experimentalFeatures: true + } +}) +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/security_electronjs.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/security_electronjs.yaml new file mode 100644 index 0000000..a80b9b8 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/security_electronjs.yaml @@ -0,0 +1,99 @@ +rules: + - id: electron_disable_websecurity + patterns: + - pattern-either: + - pattern: | + new BrowserWindow({webPreferences: {webSecurity: false}}); + - pattern: | + var $X = {webPreferences: {webSecurity: false}}; + message: >- + Disabling webSecurity will disable the same-origin policy and allows the + execution of insecure code from any domain. + languages: + - javascript + severity: ERROR + metadata: + owasp: A6 - Security Misconfiguration + cwe: 'CWE-346: Origin Validation Error' + - id: electron_allow_http + patterns: + - pattern-either: + - pattern: > + new BrowserWindow({webPreferences: {allowRunningInsecureContent: + true}}); + - pattern: | + var $X = {webPreferences: {allowRunningInsecureContent: true}}; + message: >- + Application can load content over HTTP and that makes the app vulnerable + to Man in the middle attacks. + languages: + - javascript + severity: ERROR + metadata: + owasp: A6 - Security Misconfiguration + cwe: 'CWE-319: Cleartext Transmission of Sensitive Information' + - id: electron_blink_integration + patterns: + - pattern-either: + - pattern: | + new BrowserWindow({webPreferences: {enableBlinkFeatures: '...'}}); + - pattern: | + var $X = {webPreferences: {enableBlinkFeatures: '...'}}; + message: >- + Blink's expirimental features are enabled in this application. Some of the + features may affect the security of the application. + languages: + - javascript + severity: WARNING + metadata: + owasp: A6 - Security Misconfiguration + cwe: 'CWE-272: Least Privilege Violation' + - id: electron_nodejs_integration + patterns: + - pattern-either: + - pattern: | + new BrowserWindow({webPreferences: {nodeIntegration: true}}); + - pattern: | + var $X = {webPreferences: {nodeIntegration: true}}; + message: >- + Node integration exposes node.js APIs to the electron app and this can + introduce remote code execution vulnerabilities to the application if the + app is vulnerable to Cross Site Scripting (XSS). + languages: + - javascript + severity: WARNING + metadata: + owasp: A6 - Security Misconfiguration + cwe: 'CWE-272: Least Privilege Violation' + - id: electron_context_isolation + patterns: + - pattern-either: + - pattern: | + new BrowserWindow({webPreferences: {contextIsolation: false}}); + - pattern: | + var $X = {webPreferences: {contextIsolation: false}}; + message: >- + Disabling context isolation can introduce Prototype Pollution + vulnerabilities. + languages: + - javascript + severity: WARNING + metadata: + owasp: A6 - Security Misconfiguration + cwe: 'CWE-693: Protection Mechanism Failure' + - id: electron_experimental_features + patterns: + - pattern-either: + - pattern: | + new BrowserWindow({webPreferences: {experimentalFeatures: true}}); + - pattern: | + var $X = {webPreferences: {experimentalFeatures: true}}; + message: >- + Experimental features are not expected to be in production ready + applications. + languages: + - javascript + severity: WARNING + metadata: + owasp: A6 - Security Misconfiguration + cwe: 'CWE-272: Least Privilege Violation' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/server_side_template_injection.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/server_side_template_injection.ts new file mode 100644 index 0000000..7e4db32 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/server_side_template_injection.ts @@ -0,0 +1,58 @@ +var handlebars = require('handlebars'), + fs = require('fs'), + Sqrl = require('squirrelly'); +// do not match +var template = handlebars.compile(source); + +app.get('/', function (req: { foo: { [x: string]: string; bar: any; }; }, res: any) { + var storeName = "console.log(process.pid)" // this should be a user-controlled string + function getStoreName() { + return storeName; + } + var scope = { + getStoreName: getStoreName + } +// {fact rule=code-injection@v1.0 defects=1} + fs.readFile('example.html', 'utf-8', function (error: any, source: string) { + // ruleid:server_side_template_injection + var template = handlebars.compile(source + req.params.foo); +// {/fact} + +// {fact rule=code-injection@v1.0 defects=1}req + // ruleid:server_side_template_injection + handlebars.compile(source + req.params.foo.bar); +// {/fact} + +// {fact rule=code-injection@v1.0 defects=1} + + + var myTemplate = 'Hi, my name is {{name}}' + // ruleid:server_side_template_injection + var temp = myTemplate + req.params['bar'] + var compiled = Sqrl.Compile(temp) +// {/fact} + + + +// {fact rule=code-injection@v1.0 defects=1} + // ruleid:server_side_template_injection + var xx = source.replace('', req.params.foo) + handlebars.compile(xx) +// {/fact} + + + +// {fact rule=code-injection@v1.0 defects=1} + // ruleid:server_side_template_injection + var x = source + req.params.foo; + var z = 2; + handlebars.compile(x); + + var html = template(data); + console.log(html) + }); + + //do not match + var template = handlebars.compile(source); +}); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/server_side_template_injection.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/server_side_template_injection.yaml new file mode 100644 index 0000000..193d72f --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/server_side_template_injection.yaml @@ -0,0 +1,78 @@ +rules: + - id: server_side_template_injection + patterns: + - pattern-either: + - pattern-inside: | + $HB = require('handlebars'); + ... + - pattern-inside: | + $HB = require('pug'); + ... + - pattern-inside: | + $HB = require('hamljs'); + ... + - pattern-inside: | + $HB = require('ejs'); + ... + - pattern-inside: | + $HB = require('squirrelly'); + ... + - pattern-inside: | + $HB = require('eta'); + ... + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $HB.compile(..., <... $REQ.$FOO ...>, ...) + - pattern: | + $HB.compile(..., <... $REQ.$FOO.$BAR ...>, ...) + - pattern: | + $X = <... $REQ.$FOO ...>; + ... + $HB.compile(..., <... $X ...>, ...); + - pattern: | + $X = <... $REQ.$FOO.$BAR ...>; + ... + $HB.compile(..., <... $X ...>, ...); + - pattern: | + $X = $SOURCE.replace('...', <... $REQ.$FOO ...>, ...); + ... + $HB.compile(..., <... $X ...>, ...); + - pattern: | + $X = $SOURCE.replace('...', <... $REQ.$FOO.$BAR ...>, ...); + ... + $HB.compile(..., <... $X ...>, ...); + - pattern: | + $HB.Compile(..., <... $REQ.$FOO ...>, ...) + - pattern: | + $HB.Compile(..., <... $REQ.$FOO.$BAR ...>, ...) + - pattern: | + $X = <... $REQ.$FOO ...>; + ... + $HB.Compile(..., <... $X ...>, ...); + - pattern: | + $X = <... $REQ.$FOO.$BAR ...>; + ... + $HB.Compile(..., <... $X ...>, ...); + - pattern: | + $X = $SOURCE.replace('...', <... $REQ.$FOO ...>, ...); + ... + $HB.Compile(..., <... $X ...>, ...); + - pattern: | + $X = $SOURCE.replace('...', <... $REQ.$FOO.$BAR ...>, ...); + ... + $HB.Compile(..., <... $X ...>, ...); + message: >- + Untrusted user input in templating engine's compile() function can result + in Remote Code Execution via server side template injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: CWE-94 Improper Control of Generation of Code ('Code Injection') diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/sql_injection.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/sql_injection.yaml new file mode 100644 index 0000000..d814f84 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/sql_injection.yaml @@ -0,0 +1,39 @@ +rules: + - id: node_sqli_injection + patterns: + - pattern-either: + - pattern: | + $CON.query(<... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $CON.query(<... $REQ.$QUERY ...>, ...) + - pattern: | + $SQL = <... $REQ.$QUERY.$VAR ...>; + ... + $CON.query(<... $SQL ...>, ...); + - pattern: | + $SQL = <... $REQ.$QUERY ...>; + ... + $CON.query(<... $SQL ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + $SQL = <... $INP ...>; + ... + $CON.query(<... $SQL ...>, ...); + - pattern: | + $INP = <... $REQ.$QUERY ...>; + ... + $SQL = <... $INP ...>; + ... + $CON.query(<... $SQL ...>, ...); + message: >- + Untrusted input concatinated with raw SQL query can result in SQL + Injection. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-89: Improper Neutralization of Special Elements used in an SQL + Command ('SQL Injection') diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/sqli_node.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/sqli_node.ts new file mode 100644 index 0000000..8c1ccfd --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/sqli_node.ts @@ -0,0 +1,83 @@ +var mysql = require('mysql'); + +// {fact rule=sql-injection@v1.0 defects=1} +const pg = require('pg'); +// ruleid:node_sqli_injection +connection.query("SELECT * FROM bank_accounts WHERE dob = '" + req.body.dob + "' AND bank_account = '" + req.body.account_number + "'", function (error: any, results: any) { }); + +// {/fact} + +const sequelize = require('../conn'); +router.post('/', function (req: { body: { input: string; }; }, res: { json: (arg0: { message: any; }) => void; }) { +// {fact rule=sql-injection@v1.0 defects=1} + // ruleid:node_sqli_injection + var query = 'SELECT * FROM person WHERE id = \'' + + req.body.input + '\''; + sequelize.query(query, { + type: sequelize.QueryTypes.SELECT, + model: Foo + }) + .then(function (foo: any) { + res.json({ message: person }); + }) + .catch(function (err: { toString: () => any; }) { + res.json({ message: err.toString() }); + }); +}); +// {/fact} + + +// {fact rule=sql-injection@v1.0 defects=1} +var connection = mysql.createConnection({ + host: 'localhost', + user: user, + password: pass, + database: 'technicalkeeda', + debug: false, +}); +connection.connect(); + +// ruleid:node_sqli_injection +var employeeId = req.foo; +var sql = "SELECT * FROM trn_employee WHERE employee_id = " + employeeId; + +connection.query(sql, function (error: any, results: any, fields: any) { + if (error) { + throw error; + } + console.log(results); +}); +// {/fact} + + +// {fact rule=sql-injection@v1.0 defects=1} +connection.connect(function (err: any) { + // ruleid:node_sqli_injection + connection.query('SELECT * FROM users WHERE id = ' + req.foo('bar'), (err: any, res: any) => { }); +}); + +connection.end(); +// {/fact} + + +// {fact rule=sql-injection@v1.0 defects=1} +const pgcon = new pg.Client({ host: host, user: user, password: pass, database: db }); +pgcon.connect(); +// ruleid:node_sqli_injection +var inp = req.foo["id"]; +pgcon.query('SELECT * FROM users WHERE id = ' + inp, (err: any, res: any) => { }); + +// {/fact} + + +// {fact rule=sql-injection@v1.0 defects=1} +const pg = require('pg'); +const pool = new pg.Pool(config); +function handler(req: { foo: { bar: string; }; }, res: any) { + // ruleid:node_sqli_injection + var query1 = "SELECT FOO,BAR FROM TABLE WHERE CAT='" + + req.foo.bar + "' ORDER BY FOO"; + pool.query(query1, [], function (err: any, results: any) { + }); +} +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/ssrf_node.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/ssrf_node.ts new file mode 100644 index 0000000..5360003 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/ssrf_node.ts @@ -0,0 +1,169 @@ +var express = require('express'); +import request from 'request'; +var needle = require('needle'); +var app = express(); +import bent from 'bent'; +const getJSON = bent('json') +const getBuffer = bent('buffer') +var urllib = require('urllib'); +import http from 'http'; +let axios = require('axios'); +var http = require('https'); + +// {fact rule=server-side-request-forgery@v1.0 defects=1} +app.get('/', function (req: { query: { name: any; }; vbody: { foo: any; }; foo: any; }, res: any) { + // ruleid:node_ssrf + request(req.query.name, function (error: any, response: { statusCode: any; }, body: any) { + console.error('error:', error); // Print the error if one occurred + console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received + console.log('body:', body); // Print the HTML for the Google homepage. + }); +// {/fact} + +// {fact rule=server-side-request-forgery@v1.0 defects=1} + // ruleid:node_ssrf + needle('get', req.vbody.foo).then((res: { body: any; }) => { + console.log(res.body); + }) + .catch((err: any) => { + console.error(err); + }); +// {/fact} + + +// {ex-fact rule=server-side-request-forgery@v1.0 defects=1} + // ruleid:node_ssrf + // urllib.request(req.foo, function (err: any, data: { toString: () => any; }, res: { statusCode: any; headers: any; }) { + // if (err) { + // throw err; // you need to handle error + // } + // console.log(res.statusCode); + // console.log(res.headers); + // // data is Buffer instance + // console.log(data.toString()); + // }); + +}); +// {/ex-fact} + +// {ex-fact rule=server-side-request-forgery@v1.0 defects=1} +// app.get('/', function (req: { foo: { bar: any; }; post: { doo: RequestInfo | URL; }; }, res: any) { +// +// // ruleid:node_ssrf +// needle.get(req.foo, function (error: any, response: { statusCode: number; body: any; }) { +// if (!error && response.statusCode == 200) +// console.log(response.body); +// }); + +// {/ex-fact} + +// // {ex-fact rule=server-side-request-forgery@v1.0 defects=1} +// // ruleid:node_ssrf +// needle.post(req.foo) +// .pipe(out) +// .on('finish', () => { +// console.log('pipe done'); +// }); +// +// //Do not match this +// needle.get('http://google.com') +// .pipe(out) +// .on('finish', () => { +// console.log('pipe done'); +// }); +// +// //Do not match this to reduce false positives +// needle.get(somvar) +// .pipe(out) +// .on('finish', () => { +// console.log('pipe done'); +// }); +// +// // {/ex-fact} + +// {ex-fact rule=server-side-request-forgery@v1.0 defects=1} + // ruleid:node_ssrf + // axios.get(req.foo.bar) + // .then(function (response: any) { + // // handle success + // console.log(response); + // }) + // .catch(function (error: any) { + // // handle error + // console.log(error); + // }) + // .finally(function () { + // // always executed + // }); +// {/ex-fact} + + +// {ex-fact rule=server-side-request-forgery@v1.0 defects=1} + // ruleid:node_ssrf +// let obj = await getJSON(req.foo); +// // {/ex-fact} + + // {ex-fact rule=server-side-request-forgery@v1.0 defects=1} + // ruleid:node_ssrf + // let buffer = await getBuffer(req.foo); +// {/ex-fact} + + // {fact rule=server-side-request-forgery@v1.0 defects=1} + + // ruleid:node_ssrf + fetch(req.post.doo, { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); + +}); +// {/fact} + +// {fact rule=server-side-request-forgery@v1.0 defects=1} + +app.listen(8000); + +// do not match +needle.get(foo, function (error: any, response: { statusCode: number; body: any; }) { + if (!error && response.statusCode == 200) + console.log(response.body); +}); + + +var net = require('net'); + + +app.get('/', function (req: { body: { host: any; }; foo: any; end: () => void; once: (arg0: string, arg1: (res: any) => void) => void; socket: { localAddress: any; localPort: any; }; }, res: any) { + var client = new net.Socket(); + // ruleid:node_ssrf + client.connect(1337, req.body.host, function () { + console.log('Connected'); + client.write('Hello, server! Love, Client.'); + }); + + client.on('data', function (data: string) { + console.log('Received: ' + data); + client.destroy(); // kill client after server's response + }); + + client.on('close', function () { + console.log('Connection closed'); + }); + +// {/fact} + + + + + // {ex-fact rule=server-side-request-forgery@v1.0 defects=1} + // ruleid:node_ssrf + // const fk = http.get({ host: req.foo }); + // req.end(); + // req.once('response', (res: any) => { + // const ip = req.socket.localAddress; + // const port = req.socket.localPort; + // console.log(`Your IP address is ${ip} and your source port is ${port}.`); + // // Consume response object + // }); + +}); +// {/ex-fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/ssrf_node.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/ssrf_node.yaml new file mode 100644 index 0000000..8b52cb8 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/ssrf_node.yaml @@ -0,0 +1,191 @@ +rules: + - id: node_ssrf + patterns: + - pattern-either: + - pattern-inside: | + $PKG = require('request'); + ... + - pattern-inside: | + $PKG = require('axios'); + ... + - pattern-inside: | + $PKG = require('needle'); + ... + - pattern-inside: | + $PKG = require('bent'); + ... + - pattern-inside: | + $PKG = require('urllib'); + ... + - pattern-inside: | + $PKG = require('net'); + ... + - pattern-inside: | + $PKG = require('https'); + ... + - pattern-inside: | + $PKG = require('superagent'); + ... + - pattern-inside: | + $PKG = require('got'); + ... + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $PKG.get(<... $REQ.$VAR ...>, ...) + - pattern: | + $PKG.get(<... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + $PKG.post(<... $REQ.$VAR ...>, ...) + - pattern: | + $PKG.post(<... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + $PKG.put(<... $REQ.$VAR ...>, ...) + - pattern: | + $PKG.put(<... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + needle("=~/[get|post|put|GET|POST|PUT]+/", <... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + needle("=~/[get|post|put|GET|POST|PUT]+/", <... $REQ.$VAR ...>, ...) + - pattern: | + request(<... $REQ.$VAR ...>, ...) + - pattern: | + request(<... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + $PKG.request(<... $REQ.$VAR ...>, ...) + - pattern: | + $PKG.request(<... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + getJSON(<... $REQ.$VAR ...>, ...) + - pattern: | + getJSON(<... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + getBuffer(<... $REQ.$VAR ...>, ...) + - pattern: | + getBuffer(<... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + fetch(<... $REQ.$VAR ...>, ...) + - pattern: | + fetch(<... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + $SOCKET.connect($PORT, <... $REQ.$VAR ...>, ...) + - pattern: | + $SOCKET.connect($PORT, <... $REQ.$VAR.$FOO ...>, ...) + - pattern: | + $PKG.get(..., {host: <... $REQ.$VAR ...>}, ...) + - pattern: | + $PKG.get(..., {host: <... $REQ.$VAR.$FOO ...>}, ...) + - pattern: | + $PKG.get(..., {hostname: <... $REQ.$VAR ...>}, ...) + - pattern: | + $PKG.get(..., {hostname: <... $REQ.$VAR.$FOO ...>}, ...) + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $PKG.get(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + $PKG.get(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $PKG.post(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + $PKG.post(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $PKG.put(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + $PKG.put(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + needle("=~/[get|post|put|GET|POST|PUT]+/", <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + needle("=~/[get|post|put|GET|POST|PUT]+/", <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + request(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + request(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $PKG.request(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + $PKG.request(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + getJSON(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + getJSON(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + getBuffer(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + getBuffer(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + fetch(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + fetch(<... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $SOCKET.connect($PORT, <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + $SOCKET.connect($PORT, <... $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $PKG.get(..., {host: <... $INP ...>}, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + $PKG.get(..., {host: <... $INP ...>}, ...); + - pattern: | + $INP = <... $REQ.$VAR ...>; + ... + $PKG.get(..., {hostname: <... $INP ...>}, ...); + - pattern: | + $INP = <... $REQ.$VAR.$FOO ...>; + ... + $PKG.get(..., {hostname: <... $INP ...>}, ...); + message: >- + User controlled URL in http client libraries can result in Server Side + Request Forgery (SSRF). + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: 'CWE-918: Server-Side Request Forgery (SSRF)' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/timing_attack_node.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/timing_attack_node.yaml new file mode 100644 index 0000000..559d4d1 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/timing_attack_node.yaml @@ -0,0 +1,494 @@ +# Rule inspired from: https://github.com/nodesecurity/eslint-plugin-security/blob/master/rules/detect-possible-timing-attacks.js +rules: + - id: node_timing_attack + patterns: + - pattern-not: if ($Z == null) { ... }; + - pattern-not: if ($Z === null) { ... }; + - pattern-not: if ($Z != null) { ... }; + - pattern-not: if ($Z !== null) { ... }; + - pattern-not: if ($Q != undefined) { ... }; + - pattern-not: if ($Q !== undefined) { ... }; + - pattern-not: if ($Q == undefined) { ... }; + - pattern-not: if ($Q === undefined) { ... }; + - pattern-not: return $Y == null; + - pattern-not: return $Y === null; + - pattern-not: return $Y != null; + - pattern-not: return $Y !== null; + - pattern-not: return $Y == undefined; + - pattern-not: return $Y === undefined; + - pattern-not: return $Y != undefined; + - pattern-not: return $Y !== undefined; + - pattern-either: + - pattern: | + if (password == $X) { + ... + } + - pattern: | + if ($X == password) { + ... + } + - pattern: | + if (password === $X) { + ... + } + - pattern: | + if ($X === password) { + ... + } + - pattern: | + if (pass == $X) { + ... + } + - pattern: | + if ($X == pass) { + ... + } + - pattern: | + if (pass === $X) { + ... + } + - pattern: | + if ($X === pass) { + ... + } + - pattern: | + if (secret == $X) { + ... + } + - pattern: | + if ($X == secret) { + ... + } + - pattern: | + if (secret === $X) { + ... + } + - pattern: | + if ($X === secret) { + ... + } + - pattern: | + if (api == $X) { + ... + } + - pattern: | + if ($X == api) { + ... + } + - pattern: | + if (api === $X) { + ... + } + - pattern: | + if ($X === api) { + ... + } + - pattern: | + if (apiKey == $X) { + ... + } + - pattern: | + if ($X == apiKey) { + ... + } + - pattern: | + if (apiKey === $X) { + ... + } + - pattern: | + if ($X === apiKey) { + ... + } + - pattern: | + if (apiSecret == $X) { + ... + } + - pattern: | + if ($X == apiSecret) { + ... + } + - pattern: | + if (apiSecret === $X) { + ... + } + - pattern: | + if ($X === apiSecret) { + ... + } + - pattern: | + if (token == $X) { + ... + } + - pattern: | + if ($X == token) { + ... + } + - pattern: | + if (token === $X) { + ... + } + - pattern: | + if ($X === token) { + ... + } + - pattern: | + if (hash == $X) { + ... + } + - pattern: | + if ($X == hash) { + ... + } + - pattern: | + if (hash === $X) { + ... + } + - pattern: | + if ($X === hash) { + ... + } + - pattern: | + if (auth_token == $X) { + ... + } + - pattern: | + if ($X == auth_token) { + ... + } + - pattern: | + if (auth_token === $X) { + ... + } + - pattern: | + if ($X === auth_token) { + ... + } + - pattern: | + if (password != $X) { + ... + } + - pattern: | + if ($X != password) { + ... + } + - pattern: | + if (password !== $X) { + ... + } + - pattern: | + if ($X !== password) { + ... + } + - pattern: | + if (pass != $X) { + ... + } + - pattern: | + if ($X != pass) { + ... + } + - pattern: | + if (pass !== $X) { + ... + } + - pattern: | + if ($X !== pass) { + ... + } + - pattern: | + if (secret != $X) { + ... + } + - pattern: | + if ($X != secret) { + ... + } + - pattern: | + if (secret !== $X) { + ... + } + - pattern: | + if ($X !== secret) { + ... + } + - pattern: | + if (api != $X) { + ... + } + - pattern: | + if ($X != api) { + ... + } + - pattern: | + if (api !== $X) { + ... + } + - pattern: | + if ($X !== api) { + ... + } + - pattern: | + if (apiKey != $X) { + ... + } + - pattern: | + if ($X != apiKey) { + ... + } + - pattern: | + if (apiKey !== $X) { + ... + } + - pattern: | + if ($X !== apiKey) { + ... + } + - pattern: | + if (apiSecret != $X) { + ... + } + - pattern: | + if ($X != apiSecret) { + ... + } + - pattern: | + if (apiSecret !== $X) { + ... + } + - pattern: | + if ($X !== apiSecret) { + ... + } + - pattern: | + if (token != $X) { + ... + } + - pattern: | + if ($X != token) { + ... + } + - pattern: | + if (token !== $X) { + ... + } + - pattern: | + if ($X !== token) { + ... + } + - pattern: | + if (hash != $X) { + ... + } + - pattern: | + if ($X != hash) { + ... + } + - pattern: | + if (hash !== $X) { + ... + } + - pattern: | + if ($X !== hash) { + ... + } + - pattern: | + if (auth_token != $X) { + ... + } + - pattern: | + if ($X != auth_token) { + ... + } + - pattern: | + if (auth_token !== $X) { + ... + } + - pattern: | + if ($X !== auth_token) { + ... + } + - pattern: | + return $X === auth_token; + - pattern: | + return auth_token === $X; + - pattern: | + return $X === token; + - pattern: | + return token === $X; + - pattern: | + return $X === hash; + - pattern: | + return hash === $X; + - pattern: | + return $X === password; + - pattern: | + return password === $X; + - pattern: | + return $X === pass; + - pattern: | + return pass === $X; + - pattern: | + return $X === apiKey; + - pattern: | + return apiKey === $X; + - pattern: | + return $X === apiSecret; + - pattern: | + return apiSecret === $X; + - pattern: | + return $X === api_key; + - pattern: | + return api_key === $X; + - pattern: | + return $X === api_secret; + - pattern: | + return api_secret === $X; + - pattern: | + return $X === secret; + - pattern: | + return secret === $X; + - pattern: | + return $X === api; + - pattern: | + return api === $X; + - pattern: | + return $X == auth_token; + - pattern: | + return auth_token == $X; + - pattern: | + return $X == token; + - pattern: | + return token == $X; + - pattern: | + return $X == hash; + - pattern: | + return hash == $X; + - pattern: | + return $X == password; + - pattern: | + return password == $X; + - pattern: | + return $X == pass; + - pattern: | + return pass == $X; + - pattern: | + return $X == apiKey; + - pattern: | + return apiKey == $X; + - pattern: | + return $X == apiSecret; + - pattern: | + return apiSecret == $X; + - pattern: | + return $X == api_key; + - pattern: | + return api_key == $X; + - pattern: | + return $X == api_secret; + - pattern: | + return api_secret == $X; + - pattern: | + return $X == secret; + - pattern: | + return secret == $X; + - pattern: | + return $X == api; + - pattern: | + return api == $X; + - pattern: | + return $X !== auth_token; + - pattern: | + return auth_token !== $X; + - pattern: | + return $X !== token; + - pattern: | + return token !== $X; + - pattern: | + return $X !== hash; + - pattern: | + return hash !== $X; + - pattern: | + return $X !== password; + - pattern: | + return password !== $X; + - pattern: | + return $X !== pass; + - pattern: | + return pass !== $X; + - pattern: | + return $X !== apiKey; + - pattern: | + return apiKey !== $X; + - pattern: | + return $X !== apiSecret; + - pattern: | + return apiSecret !== $X; + - pattern: | + return $X !== api_key; + - pattern: | + return api_key !== $X; + - pattern: | + return $X !== api_secret; + - pattern: | + return api_secret !== $X; + - pattern: | + return $X !== secret; + - pattern: | + return secret !== $X; + - pattern: | + return $X !== api; + - pattern: | + return api !== $X; + - pattern: | + return $X != auth_token; + - pattern: | + return auth_token != $X; + - pattern: | + return $X != token; + - pattern: | + return token != $X; + - pattern: | + return $X != hash; + - pattern: | + return hash != $X; + - pattern: | + return $X != password; + - pattern: | + return password != $X; + - pattern: | + return $X != pass; + - pattern: | + return pass != $X; + - pattern: | + return $X != apiKey; + - pattern: | + return apiKey != $X; + - pattern: | + return $X != apiSecret; + - pattern: | + return apiSecret != $X; + - pattern: | + return $X != api_key; + - pattern: | + return api_key != $X; + - pattern: | + return $X != api_secret; + - pattern: | + return api_secret != $X; + - pattern: | + return $X != secret; + - pattern: | + return secret != $X; + - pattern: | + return $X != api; + - pattern: | + return api != $X; + message: >- + String comparisons using '===', '!==', '!=' and '==' is vulnerable to timing attacks. + More info: https://snyk.io/blog/node-js-timing-attack-ccc-ctf/ + languages: + - javascript + severity: WARNING + metadata: + owasp: 'A9: Using Components with Known Vulnerabilities' + cwe: 'CWE-208: Observable Timing Discrepancy' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/tls_node.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/tls_node.ts new file mode 100644 index 0000000..3d401c4 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/tls_node.ts @@ -0,0 +1,62 @@ +var request = require('request'); +var use_key = 'e0ee2bc6d1979f49c6437e27b06a0101'; + +//corresponding function for each api call to tortuga gateway, allows easy calling and can store user key + +module.exports = { +// {fact rule=improper-certificate-validation@v1.0 defects=1} + 'status': function (callback: (arg0: any, arg1: undefined) => void) { + // ruleid:node_tls_reject + process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'; + request.get('https://dev.app.idt.net/v1/status?user_key=' + use_key, function (err: any, response: any, body: string) { + if (err) callback(err); + + var status = JSON.parse(body); + callback(err, status); + }) + }, +// {/fact} + + // {fact rule=improper-certificate-validation@v1.0 defects=1} + 'fund': function (json: any, callback: (arg0: any, arg1: undefined) => void) { + // ruleid:node_tls_reject + process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; + request.post({ + uri: 'https://dev.app.idt.net/v1/charges?user_key=' + use_key, + json: json, + method: 'POST' + }, + function (err: any, response: any, body: any) { + if (err) callback(err); + + callback(err, response); + }) + + }, +} +// {/fact} + + +// {fact rule=improper-certificate-validation@v1.0 defects=1} +var http = require('http'); +var curl = require('node-curl'); + +http.createServer(function (request: { url: string; }, response: { end: (arg0: any) => void; }) { + + var url = 'https://url'; + url += request.url; + + console.log(url); + + + // ruleid:node_curl_ssl_verify_disable + curl(url, + { + SSL_VERIFYPEER: 0 + }, + function (err: any) { + response.end(this.body); + }) + +}).listen(8000); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/tls_node.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/tls_node.yaml new file mode 100644 index 0000000..a22881e --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/tls_node.yaml @@ -0,0 +1,28 @@ +rules: + - id: node_tls_reject + patterns: + - pattern-either: + - pattern: | + $X.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' + - pattern: | + $X.env['NODE_TLS_REJECT_UNAUTHORIZED']= '0' + message: >- + Setting 'NODE_TLS_REJECT_UNAUTHORIZED' to 0 will allow node server to + accept self signed certificates and is not an secure behaviour. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: 'CWE-295: Improper Certificate Validation' + - id: node_curl_ssl_verify_disable + patterns: + - pattern: | + $X(..., {SSL_VERIFYPEER : 0}, ...) + message: SSL Certificate verification for node-curl is disabled. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A6: Security Misconfiguration' + cwe: 'CWE-599: Missing Validation of OpenSSL Certificate' diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xml_entity_expansion.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xml_entity_expansion.ts new file mode 100644 index 0000000..bab5ee7 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xml_entity_expansion.ts @@ -0,0 +1,7 @@ +// {fact rule=xml-external-entity@v1.0 defects=1} +app.get('/expat', function (req: { param: (arg0: string) => any; }, res: any) { + // ruleid:node_entity_expansion + var parser = new expat.Parser(); + parser.write(req.param("xml")); +}) +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xml_entity_expansion_dos.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xml_entity_expansion_dos.yaml new file mode 100644 index 0000000..f095bdc --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xml_entity_expansion_dos.yaml @@ -0,0 +1,31 @@ +rules: + - id: node_entity_expansion + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $PARSER = new expat.Parser(); + ... + $PARSER.write(..., <... $REQ.$QUERY ...>, ...); + - pattern: | + $PARSER = new expat.Parser(); + ... + $PARSER.write(..., <... $REQ.$QUERY.$FOO ...>, ...); + - pattern: | + $PARSER = new expat.Parser(); + ... + $PARSER.write(..., <... $REQ.$QUERY.$FOO.$FILE ...>, ...); + message: >- + User controlled data in XML Parsers can result in + XML Internal Entity Processing vulnerabilities like in DoS. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A4: XML External Entities (XXE)' + cwe: "CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')" diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xpathi_node.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xpathi_node.ts new file mode 100644 index 0000000..110c83b --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xpathi_node.ts @@ -0,0 +1,31 @@ +var xpath = require('xpath'); +var express = require('express'); + +var app = express(); + +app.get('/xpath', function (req: { [x: string]: string; param: string; }, res: { redirect: (arg0: string) => void; }) { + // {fact rule=xpath-injection@v1.0 defects=1} + // ruleid:node_xpath_injection + var expr = xpath.parse("//persons/user[name/text()='" + req.param("name") + "']/details/text()"); +// {/fact} + + // {fact rule=xpath-injection@v1.0 defects=1} + // ruleid:node_xpath_injection + expr = xpath.parse("//persons/user[name/text()='" + req.param.name + "']/details/text()"); +// {/fact} + + // {fact rule=xpath-injection@v1.0 defects=1} + // ruleid:node_xpath_injection + expr = xpath.parse("//persons/user[name/text()='" + req["name"] + "']/details/text()"); +// {/fact} + + // {fact rule=xpath-injection@v1.0 defects=1} + // ruleid:node_xpath_injection + var foo = req.param; + expr = xpath.parse("//persons/user[name/text()='" + foo + "']/details/text()"); + //do not match + expr = JSON.parse("{'foo':" + req.param + "}"); + res.redirect('/home') +}); +// {/fact} + diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xpathi_node.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xpathi_node.yaml new file mode 100644 index 0000000..31ecbfe --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xpathi_node.yaml @@ -0,0 +1,57 @@ +rules: + - id: node_xpath_injection + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $XPATH.parse(<... "=~/[\/\/].+/" + $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $XPATH.parse(<... "=~/[\/\/].+/" + $REQ.$PARAM ...>, ...) + - pattern: | + $XPATH.parse(<... "=~/[\/\/].+/" + $REQ.$PARAM["..."] ...>, ...) + - pattern: | + $XPATH.parse(<... "=~/[\/\/].+/" + $REQ.$PARAM("...") ...>, ...) + - pattern: | + $XPATH.parse(<... "=~/[\/\/].+/" + $REQ["..."] ...>, ...) + - pattern: | + $XPATH.parse(<... "=~/[\/\/].+/" + $REQ("...") ...>, ...) + - pattern: | + $INP = <... $REQ.$QUERY.$VAR ...>; + ... + $XPATH.parse(<... "=~/[\/\/].+/" + $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$PARAM...>; + ... + $XPATH.parse(<... "=~/[\/\/].+/" + $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$PARAM["..."] ...>; + ... + $XPATH.parse(<... "=~/[\/\/].+/" + $INP ...>, ...); + - pattern: | + $INP = <... $REQ.$PARAM("...") ...>; + ... + $XPATH.parse(<... "=~/[\/\/].+/" + $INP ...>, ...); + - pattern: | + $INP = <... $REQ["..."] ...>; + ... + $XPATH.parse(<... "=~/[\/\/].+/" + $INP ...>, ...); + - pattern: | + $INP = <... $REQ("...") ...>; + ... + $XPATH.parse(<... "=~/[\/\/].+/" + $INP ...>, ...); + message: >- + User controlled data in xpath.parse() can result in XPATH injection + vulnerability. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-643: Improper Neutralization of Data within XPath Expressions + ('XPath Injection') diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_node.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_node.ts new file mode 100644 index 0000000..3908e58 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_node.ts @@ -0,0 +1,160 @@ +import express from 'express'; +const router = express.Router() + +// {fact rule=cross-site-scripting@v1.0 defects=1} +router.get('/greeting', (req: { query: { name: any; }; }, res: { send: (arg0: string) => void; }) => { + // ruleid:express_xss + const { name } = req.query; + res.send('

Hello :' + name + "

") +}) + +//template handle escaping +router.get('/greet-template', (req: { query: { name: any; }; }, res: { render: (arg0: string, arg1: { user_name: void; }) => void; }) => { + name = req.query.name + res.render('index', { user_name: name }); +}) + +module.exports = router +// {/fact} + + + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/', function (req: { query: { name: any; }; }, res: { send: (arg0: string) => void; }) { + // ruleid:express_xss + var user = req.query.name; + + msg = "Hi " + user + res.send('Response
' + msg); +}); + +// {/fact} + + +// {fact rule=cross-site-scripting@v1.0 defects=1} +var msg = ''; +app.get('/3', function (req: { query: { name: any; }; }, res: { send: (arg0: string) => void; }) { + // ruleid:express_xss + var user = req.query.name; + + msg = "Hi " + user + res.send('Response
' + msg); +}); + +// {/fact} + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/2', function (req: { query: { name: any; }; }, res: { send: (arg0: string) => void; }) { + // ruleid:express_xss + var user = { user: req.query.name }; + res.send('Response
' + user.name); +}); +// {/fact} + + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/1', function (req: { query: { name: any; }; }, res: { send: (arg0: string) => void; }) { + // ruleid:express_xss + var user = req.query.name; + var msg = []; + msg.push(user); + res.send('Response
' + msg[0]); +}); +// {/fact} + + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/4', function (req: { query: { name: any; }; }, res: { send: (arg0: string) => void; }) { + var user = req.query.name; + var header = ""; + var msg = 'Hi ' + user; + var footer = ""; + var output = header + msg + footer; + res.send(output); +}); +// {/fact} + + + + + + +// {fact rule=cross-site-scripting@v1.0 defects=1} +var express = require('express'); +var app = express(); +app.get('/', function (req: { query: { name: any; }; }, res: { send: (arg0: string) => void; }) { + // ruleid:express_xss + var resp = req.query.name; + res.send('Response
' + resp); +}); +// {/fact} + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/3', function (req: { query: { name: any; }; }, res: { write: (arg0: string) => void; }) { + // ruleid:express_xss + var resp = req.query.name; + res.write('Response
' + resp); +}); +// {/fact} + + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/3', function (req: { foo: any; }, res: { write: (arg0: string) => void; }) { + // ruleid:express_xss + var resp = req.params.foo; + var x = 1; + res.write('Response
' + resp); +}); +// {/fact} + + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/xss', function (req: { query: { name: string; }; }, res: { write: (arg0: string) => void; }) { + // ruleid:express_xss + var html = "ASadad" + req.query.name + "Asdadads" + res.write('Response
' + html); +}); +// {/fact} + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/xss', function (req: { query: (arg0: string) => string; }, res: { write: (arg0: string) => void; }) { + // ruleid:express_xss + res.write('Response
' + req.query('doo')); +}); +// {/fact} + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/xss', function (req: { query: { name: string; }; }, res: { write: (arg0: string) => void; }) { + // ruleid:express_xss + res.write('Response
' + req.query.name); +}); +// {/fact} + +// We are considering only non-compliant cases of Semgrep Nodejs dataset in benchmarking for now. +// this case is complaint hence commented out this case. +// {ex-fact rule=cross-site-scripting@v1.0 defects=0} +//app.get('/noxss', function (req, res) { +// var resp = req.query.name; +// res.write('Response
'); +//}); +// {/ex-fact} + + +// We cant be sure if `foo` is taintd or not. GQL considers this case as compliant. +// {fact rule=cross-site-scripting@v1.0 defects=0} +app.get('/noxs2s', function (req: { query: { name: any; }; }, res: { write: (arg0: string) => void; }) { + var resp = req.query.name; + res.write('Response
' + foo); +}); +// {/fact} + + +// {fact rule=cross-site-scripting@v1.0 defects=1} +app.get('/xss', function (req: { query: { name: any; }; }, res: { write: (arg0: string) => void; }) { + // ruleid:express_xss + var resp = req.query.name; + var html = "ASadad" + resp + "Asdadads" + res.write('Response
' + html); +}); +app.listen(8000); +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_node.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_node.yaml new file mode 100644 index 0000000..741fa55 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_node.yaml @@ -0,0 +1,137 @@ +rules: + - id: express_xss + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $RES.write(..., <... $REQ.$QUERY ...>, ...); + - pattern: | + $RES.write(..., <... $REQ.$QUERY.$FOO ...>, ...); + - pattern: | + $RES.send(..., <... $REQ.$QUERY ...>, ...); + - pattern: | + $RES.send(..., <... $REQ.$QUERY.$FOO ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY ...>; + ... + $RES.write(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY.$FOO ...>; + ... + $RES.write(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY.$VAR ...>; + ... + $RES.send(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY ...>; + ... + $RES.send(..., <... $LOCALVAR ...>, ...); + - pattern: | + var {$LOCALVAR} = <... $REQ.$QUERY.$FOO ...>; + ... + $RES.write(..., <... $LOCALVAR ...>, ...); + - pattern: | + var {$LOCALVAR} = <... $REQ.$QUERY.$VAR ...>; + ... + $RES.send(..., <... $LOCALVAR ...>, ...); + - pattern: | + var {$LOCALVAR} = <... $REQ.$QUERY ...>; + ... + $RES.send(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR = {$KEY: <... $REQ.$QUERY ...>}; + ... + $RES.write(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR = {$KEY: <... $REQ.$QUERY.$FOO ...>}; + ... + $RES.write(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR = {$KEY: <... $REQ.$QUERY.$VAR ...>}; + ... + $RES.send(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR = {$KEY: <... $REQ.$QUERY ...>}; + ... + $RES.send(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR.push(<... $REQ.$QUERY ...>); + ... + $RES.write(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR.push(<... $REQ.$QUERY.$FOO ...>); + ... + $RES.write(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR.push(<... $REQ.$QUERY.$VAR ...>); + ... + $RES.send(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR.push(<... $REQ.$QUERY ...>); + ... + $RES.send(..., <... $LOCALVAR ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY ...>; + ... + $ARR.push(<...$LOCALVAR...>); + ... + $RES.write(..., <... $ARR ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY.$FOO ...>; + ... + $ARR.push(<...$LOCALVAR...>); + ... + $RES.write(..., <... $ARR ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY.$VAR ...>; + ... + $ARR.push(<...$LOCALVAR...>); + ... + $RES.send(..., <... $ARR ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY ...>; + ... + $ARR.push(<...$LOCALVAR...>); + ... + $RES.send(..., <... $ARR ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY ...>; + ... + $OUT = <... $LOCALVAR ...>; + ... + $RES.write(..., <... $OUT ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY.$FOO ...>; + ... + $OUT = <... $LOCALVAR ...>; + ... + $RES.write(..., <... $OUT ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY.$VAR ...>; + ... + $OUT = <... $LOCALVAR ...>; + ... + $RES.send(..., <... $OUT ...>, ...); + - pattern: | + $LOCALVAR = <... $REQ.$QUERY ...>; + ... + $OUT = <... $LOCALVAR ...>; + ... + $RES.send(..., <... $OUT ...>, ...); + message: >- + Untrusted User Input in Response will result in Reflected Cross Site + Scripting Vulnerability. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-79: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_templates.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_templates.ts new file mode 100644 index 0000000..50df07c --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_templates.ts @@ -0,0 +1,45 @@ +import Sqrl from 'squirrelly'; + +// {fact rule=cross-site-scripting@v1.0 defects=0} + function name() { + var x = '

hell0

' + // ruleid:handlebars_safestring + var y = new Handlebars.SafeString(x); +// {/fact} + +// {fact rule=cross-site-scripting@v1.0 defects=0} + // ruleid:handlebars_safestring + return new Handlebars.SafeString(''); +} +// {/fact} + + +// {fact rule=cross-site-scripting@v1.0 defects=0} +function test2() { + var x = 'foooo' + var z = new Handlebars; + // ruleid:handlebars_safestring + var xx = z.SafeString(x) + return xx; +} +// {/fact} + + +// GQL cant be sure if the variable `source` is not an external input or not. The case is compliant as per GQL and non-compliant. Marking it intentional. +// {ex-fact rule=cross-site-scripting@v1.0 defects=1} +// ruleid:handlebars_noescape +var template = Handlebars.compile(source, { noEscape: true }); +var template = "This is {{target}}"; +var target = "user's pictures"; +// {/ex-fact} + +// GQL cant be sure if the variable `template` is not an external input or not. The case is compliant as per GQL and non-compliant. Marking it intentional. +// {ex-fact rule=cross-site-scripting@v1.0 defects=1} +// ruleid:handlebars_noescape +var result = Handlerbars.compile(template, { noEscape: true })({ target: target }); +// {/ex-fact} + +// {fact rule=cross-site-scripting@v1.0 defects=1} +// ruleid:squirrelly_autoescape +Sqrl.autoEscaping(false) +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_templates.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_templates.yaml new file mode 100644 index 0000000..ef6b5d5 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xss_templates.yaml @@ -0,0 +1,44 @@ +rules: + - id: handlebars_safestring + pattern-either: + - pattern: $X.SafeString(...) + - pattern: new Handlebars.SafeString(...) + message: >- + Handlebars SafeString will not escape the data passed through it. + Untrusted user input passing through SafeString can cause XSS. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-79: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') + - id: handlebars_noescape + patterns: + - pattern: | + $X.compile(..., {noEscape: true}, ...) + message: >- + Disabling Escaping in Handlebars is not a secure behaviour. This can + introduce XSS vulnerabilties. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-80: Improper Neutralization of Script-Related HTML Tags in a Web + Page (Basic XSS) + - id: squirrelly_autoescape + pattern: $X.autoEscaping(false) + message: >- + Handlebars SafeString will not escape the data passed through it. + Untrusted user input passing through SafeString can cause XSS. + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A1: Injection' + cwe: >- + CWE-79: Improper Neutralization of Input During Web Page Generation + ('Cross-site Scripting') \ No newline at end of file diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xxe_node.ts b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xxe_node.ts new file mode 100644 index 0000000..a62637c --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xxe_node.ts @@ -0,0 +1,71 @@ + +const libxmljs = require('libxmljs'); +// {fact rule=xml-external-entity@v1.0 defects=1} +app.get('/noent', function (req: { param: (arg0: string) => any; }, res: any) { + // entity expansion + // ruleid:node_xxe + libxmljs.parseXml(req.param("xml"), { noent: true }); +}); +// {/fact} + + + +// {fact rule=xml-external-entity@v1.0 defects=1} +app.get('/sax', function (req: { param: (arg0: string) => any; }, res: any) { + // SAX parser expands external entities + // ruleid:node_xxe + const parser = new libxmljs.SaxParser(); + const x = 1 + parser.parseString(req.param("xml")); +}); + +// {/fact} + + +// {fact rule=xml-external-entity@v1.0 defects=1} +app.get('/saxpush/parser', function (req: { param: (arg0: string) => any; }, res: any) { + // SAX parser expands external entities + // ruleid:node_xxe + const parser = new libxmljs.SaxPushParser(); + const x = 1 + parser.push(req.param("some-xml")); +}); + +// {/fact} + + +// {fact rule=xml-external-entity@v1.0 defects=1} +app.get('/sax', function (req: { files: { products: { data: any; }; }; }, res: any) { + // SAX parser expands external entities + const parser = new libxmljs.SaxParser(); + const x = 1 + // ruleid:node_xxe + var products = parser.parseXmlString(req.files.products.data, { noent: true, noblanks: true }) +}) + +// {/fact} + +// {fact rule=xml-external-entity@v1.0 defects=1} +const express = require('express') +const libxmljs = require('libxml') +const db = require('db'); +const router = express.Router() + +router.post('/upload-products', (req: { files: { products: { data: any; }; }; }, res: { send: (arg0: string) => void; }) => { + // ruleid:node_xxe + const XMLfile = req.files.products.data; + const products = libxmljs.parseXmlString(XMLfile, { noent: true, noblanks: true }) + + products.root().childNodes().forEach((product: { childNodes: () => { text: () => any; }[]; }) => { + let newProduct = new db.Product() + newProduct.name = product.childNodes()[0].text() + newProduct.description = product.childNodes()[3].text() + newProduct.save() + }); + + res.send('Thanks') +}) + +module.exports = router + +// {/fact} diff --git a/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xxe_node.yaml b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xxe_node.yaml new file mode 100644 index 0000000..d1b1c09 --- /dev/null +++ b/PR_12_typescript/semgrep-nodejs-js-transpile-typescript/nodejsscan/xxe_node.yaml @@ -0,0 +1,110 @@ +rules: + - id: node_xxe + patterns: + - pattern-either: + - pattern-inside: function ($REQ, $RES, ...) {...} + - pattern-inside: function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: $X = function $FUNC($REQ, $RES, ...) {...} + - pattern-inside: var $X = function $FUNC($REQ, $RES, ...) {...}; + - pattern-inside: $APP.$METHOD(..., function $FUNC($REQ, $RES, ...) {...}) + - pattern-either: + - pattern: | + $LIBXML.parseXmlString(..., <... $REQ.$QUERY.$VAR.$FILE ...>, ...) + - pattern: | + $LIBXML.parseXmlString(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $LIBXML.parseXmlString(..., <... $REQ.$QUERY ...>, ...) + - pattern: > + $FOO = <... $REQ.$QUERY.$VAR.$FILE ...>; ... + $LIBXML.parseXmlString(..., <... $FOO ...>, ...); + - pattern: > + $FOO = <... $REQ.$QUERY.$VAR ...>; ... $LIBXML.parseXmlString(..., + <... $FOO ...>, ...); + - pattern: > + $FOO = <... $REQ.$QUERY ...>; ... $LIBXML.parseXmlString(..., <... + $FOO ...>, ...); + - pattern: | + $LIBXML.parseXml(..., <... $REQ.$QUERY.$VAR.$FILE ...>, ...) + - pattern: | + $LIBXML.parseXml(..., <... $REQ.$QUERY.$VAR ...>, ...) + - pattern: | + $LIBXML.parseXml(..., <... $REQ.$QUERY ...>, ...) + - pattern: > + $FOO = <... $REQ.$QUERY.$VAR.$FILE ...>; ... $LIBXML.parseXml(..., + <... $FOO ...>, ...); + - pattern: > + $FOO = <... $REQ.$QUERY.$VAR ...>; ... $LIBXML.parseXml(..., <... + $FOO ...>, ...); + - pattern: | + $FOO = <... $REQ.$QUERY ...>; + ... + $LIBXML.parseXml(..., <... $FOO ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxParser(); + ... + $PARSER.parseString(..., <... $REQ.$QUERY ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxParser(); + ... + $PARSER.parseString(..., <... $REQ.$QUERY.$BAR ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxParser(); + ... + $PARSER.parseString(..., <... $REQ.$QUERY.$BAR.$FILE ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxPushParser(); + ... + $PARSER.push(..., <... $REQ.$QUERY ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxPushParser(); + ... + $PARSER.push(..., <... $REQ.$QUERY.$FOO ...> , ...); + - pattern: | + $PARSER = new libxmljs.SaxPushParser(); + ... + $PARSER.push(..., <... $REQ.$QUERY.$FOO.$FILE ...> , ...); + - pattern: | + $PARSER = new libxmljs.SaxParser(); + ... + $FOO = <... $REQ.$QUERY ...>; + ... + $PARSER.parseString(..., <... $FOO ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxParser(); + ... + $FOO = <... $REQ.$QUERY.$BAR ...>; + ... + $PARSER.parseString(..., <... $FOO ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxParser(); + ... + $FOO = <... $REQ.$QUERY.$BAR.$FILE ...>; + ... + $PARSER.parseString(..., <... $FOO ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxPushParser(); + ... + $FOO = <... $REQ.$QUERY ...>; + ... + $PARSER.push(..., <... $FOO ...>, ...); + - pattern: | + $PARSER = new libxmljs.SaxPushParser(); + ... + $FOO = <... $REQ.$QUERY.$BAR ...>; + ... + $PARSER.push(..., <... $FOO ...> , ...); + - pattern: | + $PARSER = new libxmljs.SaxPushParser(); + ... + $FOO = <... $REQ.$QUERY.$BAR.$FILE ...>; + ... + $PARSER.push(..., <... $FOO ...> , ...); + message: >- + User controlled data in XML parsers can result in XML External or Internal + Entity (XXE) Processing vulnerabilities + languages: + - javascript + severity: ERROR + metadata: + owasp: 'A4: XML External Entities (XXE)' + cwe: 'CWE-611: Improper Restriction of XML External Entity Reference'