🛡️ Day 4: My First Semgrep Rules and Findings

ExcelExcel
2 min read

Today, I took a big step forward in my journey into secure coding and static analysis by diving into Semgrep — a powerful tool for finding bugs, enforcing code standards, and detecting vulnerabilities in code bases.

I focused on using Semgrep with JavaScript and HTML, and here’s how it went:

✅ Installing Semgrep

Getting started was super easy. I installed Semgrep using pip:

pip install semgrep

Alternatively, you can also install it via Homebrew:

brew install semgrep

Once installed, I verified it with:

semgrep --version

📁 Testing with JS/HTML Code

I created a simple JavaScript file with some intentional vulnerabilities to test how Semgrep performs. Here's a snippet:

// vulnerable.js

// 1. Hardcoded password
function login(user) {
  var password = "supersecret123";
  authenticate(user, password);
}

// 2. Insecure eval usage
function runUserScript(script) {
  eval(script);
}

// 3. Direct DOM injection (XSS)
function displayUserInput(input) {
  document.getElementById('output').innerHTML = input;
}

// 4. Fetch with no error handling or sanitization
fetch("http://example.com/api?user=" + userInput)
  .then(response => response.json())
  .then(data => console.log(data));

I ran Semgrep against it using the default JavaScript rules:

semgrep --config p/javascript .

Boom! 🚨 It flagged:

  • The hardcoded password

  • The eval usage

  • The direct DOM injection

  • The unsanitized user input

🛠️ Writing My First Custom Rule

Next, I wrote my first custom Semgrep rule — one to detect inline JavaScript in HTML:

rules:
  - id: inline-onclick
    pattern: 'onclick="$X"'
    message: "Avoid inline JavaScript for security reasons"
    languages: [html]
    severity: WARNING

After saving it as inline-onclick.yaml, I tested it on this HTML:

<button onclick="alert('clicked!')">Click Me</button>

Semgrep flagged it just as expected!

semgrep --config inline-onclick.yaml

🔍 Key Takeaways

  • Semgrep is super lightweight and developer-friendly.

  • You can easily scan for known patterns or write your own rules.

  • It’s a must-have tool if you’re serious about secure coding.

🚀 What’s Next?

Tomorrow, I’ll be sharing how I’m starting to organize and manage my code audit projects using GitHub. From version-controlling my custom Semgrep rules to documenting findings in issues and managing branches for remediation — GitHub is becoming my audit HQ.

Stay tuned for Day 5: Managing My Audit Projects with GitHub!

0
Subscribe to my newsletter

Read articles from Excel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Excel
Excel