Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Finding flaws in code with Semgrep

After this lesson: I can scan code with Semgrep rules and judge each finding.

60 min lesson7 commandsDevSecOps lab: build a security pipeline and a gate

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A review missed one line

The college tuck shop has a small web shop. Two students reviewed every change by eye, and still a search box went live that builds its SQL from what a customer types.

People get tired. A tool that reads every line on every push does not.

By the end of this lesson

Note

I can scan code with Semgrep rules and judge each finding.

Key words

WordWhat it meansExample
SASTchecking source code for flaws without running it
Rulea pattern of code a scanner looks for
Findingone place where a rule matched
False positivea finding that is not a real flaw
Pipelinethe steps that run on every pushtest, scan, build, deploy

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A scanner reads code against rules

SAST tools read source code and never run it. Each rule describes a shape of code, such as SQL joined from strings. Every match is a finding.

Semgrep is an open-source SAST tool. A rule is a few lines of YAML, and $X in a pattern matches any expression. The shop keeps its rules in the repository, in .semgrep.yml.

Bring the lab's copy up to date

Command
docker exec gitleaks git -C /work/tuckshop pull -q

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Read the team's three rules

Command
docker exec semgrep cat /work/tuckshop/.semgrep.yml

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Scan the shop with those rules

Command
docker exec semgrep semgrep scan --config /work/tuckshop/.semgrep.yml --metrics=off /work/tuckshop

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What Semgrep found in app.py

LineRuleWhat the code does
32weak-password-hashhashes passwords with MD5
41sql-built-from-stringsjoins the search term into SQL
54shell-truepings a host named by a value
58shell-trueruns the fixed command date

The cells students fill in are left blank in this preview.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Every finding needs a judgement

Line 54 builds a command from host, so a value like x; rm -rf / would run. That is a real flaw.

Line 58 runs date with nothing added. The rule matched, but nobody can change the command. That is a false positive. Too many of them and people stop reading the report.

Try it: a rule that looks closer

Code: python
# Two lines of code. A rule that only looks for shell=True flags both.
lines = [
    'subprocess.run("ping -c 1 " + host, shell=True)',
    'subprocess.run("date -u +%Y", shell=True)',
]

for line in lines:
    naive = "shell=True" in line
    builds_command = "+" in line
    print(naive, naive and builds_command, line)

# Change the second line to add + name before the comma. What changes?

Make a free account to save your work and track your progress.

Write a sharper rule

Semgrep can say what a match must not be. pattern-not removes the calls whose command is one fixed string, written "...".

Your rule goes in /work/rules, a folder every scanner can read. The next Run writes it.

Write your own rule

Command
docker exec -i semgrep sh -c 'cat > /work/rules/shell.yml' <<'EOF'
rules:
  - id: shell-with-input
    languages: [python]
    severity: ERROR
    message: A command built from a value and run through the shell.
    patterns:
      - pattern: subprocess.run($CMD, shell=True, ...)
      - pattern-not: subprocess.run("...", shell=True, ...)
EOF

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Scan with only your rule

Command
docker exec semgrep semgrep scan --config /work/rules/shell.yml --metrics=off /work/tuckshop

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people think a scan with no findings means the code is safe. A scanner only finds what its rules describe. The lab cannot reach Semgrep's rule registry, so here it knows four shapes. Add rules for the flaws your team keeps making.

In a pipeline, the exit status decides

A pipeline step passes when its command exits 0. With --error, Semgrep exits 1 when it finds anything, so the step fails.

The JSON report is for the next step, the gate, which you meet in lesson 6.

Run it as a pipeline step

Command
docker exec semgrep semgrep scan --config /work/tuckshop/.semgrep.yml --metrics=off --config /work/rules --error --quiet --json-output=/work/reports/semgrep.json /work/tuckshop > /dev/null; echo "exit $?"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Fix the code, then the finding goes

The shop's file already holds the fixed version of each line, used when it runs with --hardened. The SQL there passes the term as a parameter, so the rule does not match it.

Read the two execute lines side by side.

Compare the two queries

Command
docker exec semgrep grep -n "like" /work/tuckshop/app.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Assignment: triage a Semgrep report

A Semgrep JSON report is a dictionary whose "results" list holds one dictionary per finding, such as {"check_id": "tuckshop.shell-true", "path": "app.py", "start": {"line": 54}, "extra": {"severity": "WARNING"}}. Write three functions.

findings(report) returns a list of (rule, path, line, severity) tuples in report order, where rule is the part of check_id after the last dot. blocking(report, level) returns the findings whose severity is at least level, on the scale INFO < WARNING < ERROR. per_rule(report) returns a dictionary from each rule to how many findings it has.

Code: python
def findings(report):
    return []


def blocking(report, level):
    return []


def per_rule(report):
    return {}

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.