1 of 80

1

Scaling Your Security Program

with Semgrep

June 17th, 2021

​

Clint Gibler | tldrsec.com

​

@clintgibler

�

2 of 80

Ambitious Claim

​

In this workshop you will:

  • Learn to write Semgrep rules
  • Roll out secret scanning (5min)
  • Replace all HTTP URLs with HTTPS (7min)
  • Find unauthenticated routes (15min)

2

3 of 80

A friendly ask 🙏

Please send me example code patterns you want to find!

We can write a rule live together ✊

3

4 of 80

whois?

me:�Clint Gibler, Head of Security Research @ r2c�Formerly: NCC Group, UC Davis PhD

​

@clintgibler

tldrsec.com���

4

r2c:�We’re an SF based static analysis startup on a mission to profoundly improve software security and reliability.

​

5 of 80

Tl;dr sec Newsletter - https://tldrsec.com

Talk summaries | Tools & Resources links | Original research

​

​

5

6 of 80

Outline

  1. Big Picture Ideas
  2. Semgrep

6

7 of 80

Outline

  • Big Picture Ideas
    1. Secure defaults >> Finding bugs
    2. The value of iteration speed
    3. Static analysis as capability, not bug finding black box
    4. The power of custom checks
    5. SAST best practices
  • Semgrep
    • Overview
    • Intro rule writing
    • New Features
    • More advanced demos

7

8 of 80

Nerd Snipe! Surprise Semgrep Challenge

https://semgrep.dev/s/clintgibler:flask-route-no-admin-annotation-try

The first person to tweet a semgrep.live Playground solution link to @clintgibler wins a Semgrep t-shirt and some stickers

​

8

9 of 80

Outline

  • Big Picture Ideas
    • Secure defaults >> Finding bugs
    • The value of iteration speed
    • Static analysis as capability, not bug finding black box
    • The power of custom checks
    • SAST best practices
  • Semgrep

9

10 of 80

Eradicating Vulnerability Classes

by Shelving SAST & Embracing Secure Defaults & Invariants

Clint Gibler

head of security research, r2c

Isaac Evans

ceo, r2c

11 of 80

Finding Bugs Only using the “safe” way

12 of 80

Detecting (lack of) use of

secure defaults

​

is much easier than

​

finding bugs

12

13 of 80

13

14 of 80

How Valuable Can Banning Functions Be?

41% of vulnerability reduction from XP → Vista from banning strcpy and friends

​

​

Analysis of 63 buffer-related security bugs that affect Windows XP, Windows Server 2003 or Windows 2000 but not Windows Vista: 82% removed through SDL process

  • 27 (43%) found through use of SAL (Annotations)
  • 26 (41%) removed through banned API removal

​

14

15 of 80

Google:

  • “It’s unreasonable to expect any developer to be an expert in all these subjects, or to constantly maintain vigilance when writing or reviewing code.
  • A better approach is to handle security and reliability in common frameworks, languages, and libraries. Ideally, libraries only expose an interface that makes writing code with common classes of security vulnerabilities impossible.”

​

15

16 of 80

Facebook:

​

​

"We invest heavily in building frameworks that help engineers prevent and remove entire classes of bugs when writing code."

​

16

17 of 80

Anecdote - a hyper growth Bay Area start-up

“We were concerned about RCE in our NodeJS applications, so we banned eval() and new Function()...”

​

Wrote custom ESlint plugins that ran on every PR that banned 👆

​

...never had to worry about these types of issues in NodeJS apps

​

“You can get amazing security wins if you can be a bit draconian about coding standards.”

​

(Caveat: of course this requires engineering buy-in, the security team must support company goals)

17

18 of 80

Dev Akhawe: PhD UC Berkeley, Dir of Security Eng Dropbox, Head of Sec Figma

“Historically, heavyweight, slow static analysis tools focused on finding vulnerabilities. This approach is fundamentally not the right path for scaling security in modern development. Security teams today need tools that are fast, customizable to our codebases, can easily be added to any part of the SDLC, and are effective at enforcing secure coding patterns to prevent vulnerabilities.��As security engineering teams define best practices, they need a scalable, low-noise mechanism to detect unsafe practices and point developers toward safe coding mechanisms. These practices are often specific to the company.

​

​

​

​

18

19 of 80

Outline

  • Big Picture Ideas
    • Secure defaults >> Finding bugs
    • The value of iteration speed
    • Static analysis as capability, not bug finding black box
    • The power of custom checks
    • SAST best practices
  • Semgrep

19

20 of 80

OODA Loop (Observe, Orient, Decide, Act)

  • Military: Originally developed by the Air Force
  • Agile dev / start-ups: faster loop → beat bigger companies
  • Blue team / Incident Response - outmaneuver attackers
    • Conversely: very hard to contain an attacker with a faster OODA loop

AppSec: Faster iteration cycles fundamentally alter how we work and think

“This is too much work, why bother.”

👀------------------------------🧠-------------------------------👍------------------------------💪

“I want to keep this from happening again. <1st attempt> <2nd> OK great roll out everywhere.”

👀--🧠--👍--💪 👀--🧠--👍--💪 👀--🧠--👍--💪 👀--🧠--👍--💪 👀--🧠--👍--💪

​

20

21 of 80

Outline

  • Big Picture Ideas
    • Secure defaults >> Finding bugs
    • The value of iteration speed
    • Static analysis as capability, not bug finding black box
    • The power of custom checks
    • SAST best practices
  • Semgrep

21

22 of 80

Dev Akhawe: PhD UC Berkeley, Dir of Security Eng Dropbox, Head of Sec Figma

...

Working with static analysis tools today is no longer a purely operational workflow, it’s a creative venture where a security engineer is building something new on top of the analysis engine.”

​

​

​

​

22

23 of 80

Static Analysis as Bug Finding Fundamental Capability

How to get your security tooling/services adopted? Provide capabilities your colleagues want

  • Visibility (asset inventory): Useful for security - need to know what we have to protect it
    • Also DevOps/SRE (troubleshooting), finance (billing), engineering (what do we have, where is it?)

​

Non-security benefits of static analysis:

  • Ensuring code standards at scale
  • Large scale code refactoring (e.g. upgrading from deprecated APIs)
  • Helping onboard new developers

23

24 of 80

Outline

  • Big Picture Ideas
    • Secure defaults >> Finding bugs
    • The value of iteration speed
    • Static analysis as capability, not bug finding black box
    • The power of custom checks
    • SAST best practices
  • Semgrep

24

25 of 80

Company-specific Checks are Often the Most Valuable

Common trend I see across a number of companies

  • Out-of-the box generic checks can provide a lot of value
    • But can be noisy, potentially few findings after initial roll out
  • Checks specific to your company can have massive ROI
    • High signal: specific to how your company writes code (coding conventions)
    • High impact: tailored to your business context and business risks
      • Detecting PII leak at an HR/healthcare firm, business logic flaws at a financial institution, …
  • Business logic bugs: (generally) no built-in SAST checks will find bugs like these
    • Neither will DAST

“We had a P1 auth bypass bug bounty submission. I wrote a quick rule to find other instances of it, and found a P0 an hour later.”

25

26 of 80

Outline

  • Big Picture Ideas
    • Secure defaults >> Finding bugs
    • The value of iteration speed
    • Static analysis as capability, not bug finding black box
    • The power of custom checks
    • SAST best practices
  • Semgrep

26

27 of 80

Choosing a Static Analysis Tool

  • Does it support the programming languages my company uses?
    • Framework (e.g. Spring, Django, …) support is also quite important
    • Tools can be better or worse at different languages/frameworks
    • Do you have a custom, inhouse framework that isn’t open source? Bad news bears.
  • Is it easy to hook into my CI systems? (GitHub Actions, Gitlab runners, CircleCI, Jenkins…)
  • Am I going to have to manage a server that runs the tool?
  • Will I have to share access to my source code?
  • Pricing
  • Is it easy to extend / customize to my environment?
    • Custom rules (specific to an org) are often the highest signal and most valuable

27

28 of 80

Rolling Out Static Analysis

Offline

Full scan of every repo - current state of the world

What vulnerability classes are most prevalent?

Make a game plan

  • Developer education
  • Update coding guidelines
  • Secure guardrails

Goal: solve classes of bugs

Continuous in CI

Roll out a few, high signal checks (stem the bleeding)

  • Partner with friendly dev teams first
  • Notify security -> PR comment -> Block

Consider choosing a vulnerability class to focus on

Pen Tests / Bug Bounty -> custom rules

  • Find other variants
  • Roll out in CI, like security integration tests

Goal: Raise your org’s security bar, one inch at a time

​

​

​

28

29 of 80

Outline

  • Big Picture Ideas
  • Semgrep
    • Overview
    • Intro rule writing
    • New Features
    • More advanced demos

29

30 of 80

​

​

30

31 of 80

Why Semgrep is 🔥 for Security Consultants / Researchers

  • Open source
  • Supports many languages
  • 1,000+ out of the box rules
  • Does not require buildable source code
  • 🔥 No painful DSL, patterns look like the code you’re targeting

31

32 of 80

Why Semgrep is 😍 for AppSec Engineers & Developers

Coding Standards ➡️ Enforce Continuously

32

33 of 80

Use Cases

  • Help new developers get up to speed faster
  • Ship higher quality code more quickly
  • Keep a high code quality standard across your organization
  • Block known bugs from re-entering a code base
  • Prevent security vulnerabilities

How can the security team provide valuable capabilities to their developer customers?

​

​

33

34 of 80

34

Semgrep

35 of 80

Our Worldview�

  • Speed matters - scan in minutes, not hours/days
  • False Negatives > False Positives
  • Ease of use is key
    • Huge value in org-specific and code base specific checks
    • Heavily prioritize first time user experience, “average” users
    • Accessible to developers, not just security professionals
  • Enforcing secure defaults > bug finding (more)

35

36 of 80

Design Decisions�

Given:

  • Speed matters
  • False Negatives > False Positives
  • Ease of use is key
  • Enforcing secure defaults > bug finding

​

Semgrep:

  • Focuses on single file / localized analysis
    • Interprocedural data flow analysis is slow/imprecise
    • Almost always sufficient for enforcing secure defaults
    • Doesn’t require buildable source, fast
  • Has rules that look like source code (can’t express everything)

​

36

37 of 80

��

Semgrep Ecosystem

How the Parts Fit Together

37

38 of 80

How Semgrep Works

38

Abstract Syntax Trees (ASTs)

Findings

(security bugs)

Pattern Matcher

Security Checks

Parser

+

Source Code

39 of 80

Semgrep Agent

39

Semgrep Agent

  • Diff-aware (only report new findings)
  • Play nicely with code hosting and CI (GitHub, GitLab, …)

​

​

​

​

​

Semgrep

40 of 80

Popular SAST Vendors

40

​

Fortify, Checkmarx

CodeQL

Semgrep

Open source rules

❌

✅

✅

Open source engine

❌

❌

✅

Freely test on closed source repos

❌

❌

✅

Open source SaaS app

❌

❌

❌

41 of 80

Semgrep Cloud

41

​

​

Semgrep Agent

​

​

​

​

​

Semgrep

​

​

Semgrep Agent

​

​

​

​

​

Semgrep

​

​

Semgrep Agent

​

​

​

​

​

Semgrep

42 of 80

Why Semgrep Cloud?

Value

  • Set scanning policy across many repos
    • (scan Rails apps with <X>, prod apps with <Y>)
  • Dashboard: metrics, trends, what’s getting fixed, what’s not
  • Integrations: email, Slack, PR comments, webhooks

Vs. Other SAST offerings

  • Your code stays in your CI system (not uploaded to r2c)
  • No infrastructure to set up/maintain/run

Vs. Rolling Your Own

  • You can! Some companies do.
  • Getting diff-aware scanning working, PR comments, integrations, etc. is possible but takes upfront engineering effort and ongoing maintenance

42

43 of 80

VS Code Extension!

43

44 of 80

Integrating into CI

https://semgrep.dev/docs/integrations/#continuous-integration-ci

  • Best supported: GitHub, GitLab

​

But any CI pipeline where you can run an CLI tool (--json) or a Docker image will work ✅

44

45 of 80

Community rule registry

45

46 of 80

Outline

  • Big Picture Ideas
  • Semgrep
    • Overview
    • Intro rule writing
    • New Features
    • More advanced demos

46

47 of 80

GitHub Learning Lab: Intro to Semgrep

https://lab.github.com/returntocorp/intro-to-semgrep

47

48 of 80

Finding Banned, Deprecated, or Dangerous Functions

48

49 of 80

Semgrep Cheat Sheet

​

49

50 of 80

#1 Code equivalence (semantic grep)

  • semgrep knows about the semantics of the language, so one pattern can match variations of equivalent code (constant propagation! https://semgrep.live/4K5)
  • ​

50

$X == $X

​

foo(kwd1=1,kwd2=2,...)

​

​

​

subprocess.open(...)

​

​

​

import foo.bar

Will match

(a+b != a+b) # <=> !(a+b==a+b)

​

foo(kwd2=2, kwd1=1, kwd3=3)

​

​

from subprocess import open as

sub_open

​

result = sub_open(“ls”)

​

from foo import bar

Will match

Will match

Will match

51 of 80

#2: ‘...’ ellipsis operator

‘…’ can match sequences of:

  • Arguments, parameters
  • Characters
  • Statements

51

foo(...,5)

​

​

foo(“...”)

​

$V = get()

...

eval($V)

​

Will match

foo(1,2,3,4,5)

foo(5)

​

foo(“whatever sequence of chars”)

​

user_data = get()

print(“do stuff”)

foobar()

eval(user_data)

Will match

Will match

52 of 80

#3 Metavariables (part 1)

  • Metavariables start with a $ ($X, $Y, $WHATEVER) , contain uppercase ASCII characters
  • Matches:
    • Expressions (including arguments)
    • Statements
    • Names (functions, fields, etc.)

52

foo($X,2)

​

if $E:

foo()

​

if $X > $Y:

$S

​

$F(1,2)

Will match

foo(1,2)

​

if x > 2:

foo()

​

if var > 2:

return 1

​

foo(1,2)

Will match

Will match

Will match

53 of 80

#3 Metavariables (part 2)

You can reuse the same metavariable: semgrep enforces equality constraint

53

$X == $X

​

if $E:

$S

else:

$S

​

​

​

$V = open()

close($V)

​

Will match

if (a+b == a+b):

​

if x > 2:

foo()

bar()

else:

foo()

bar()

​

myfile = open()

close(myfile)

​

Will match

Will match

54 of 80

Rule Syntax

54

55 of 80

Relevant Links

55

56 of 80

Outline

  • Big Picture Ideas
  • Semgrep
    • Overview
    • Intro rule writing
    • New Features
    • More advanced demos

56

57 of 80

----fast mode 🚀

Recent optimizations built-in to Semgrep, enabled now by default��Works by quickly reviewing source code contents, and then failing early if a pattern couldn’t possibly match

  • E.g. A pattern is looking for a function named foo(), but foo is not present in the file
  • More optimizations to come! (inlining patterns, caching patterns)

​

Shoutout to Yoann, Emma, & others 👉

57

58 of 80

Commutative Matching - Find A and B

58

59 of 80

metavariable-pattern

  • Run one or more Semgrep patterns on the code matched by metavariables
  • Works recursively!
  • E.g. metavar_pattern_dots_mvar.yaml | .py

59

60 of 80

metavariable-pattern

  • Run one or more Semgrep patterns on the code matched by metavariables
  • Works recursively!
  • E.g. metavar_pattern_dots_mvar.yaml | .py

60

}

}

61 of 80

metavariable-pattern

  • Run one or more Semgrep patterns on the code matched by metavariables
  • Works recursively!
  • E.g. metavar_pattern_dots_mvar.yaml | .py

61

}

}

}

62 of 80

Metavariable-pattern - can nest!

  • E.g. metavar_pattern_nested.yaml | .py

62

63 of 80

Metavariable-pattern Reduce pattern duplication

  • metavar_pattern_nested1.yaml | .py

63

64 of 80

Metavariable-pattern - Scan Polyglot Files 💪

Applications: JS in HTML, template files, React/VueJS, infra as code, Dockerfiles

64

65 of 80

Outline

  • Big Picture Ideas
  • Semgrep
    • Overview
    • Intro rule writing
    • New Features
    • More advanced demos

65

66 of 80

Combining Semgrep with Regex - pattern-regex

66

67 of 80

Weak RSA Key - Scriptable! pattern-where-python

67

* requires non-default flag: --dangerously-allow-arbitrary-code-execution-from-rules

68 of 80

Typed Patterns - Find calls to exec() on Runtime objects

68

69 of 80

JSON

69

70 of 80

Find <script> tags w/out SRI (“Generic” mode)

70

71 of 80

Terraform: Public read/write buckets (“Generic” mode)

71

Pattern:

72 of 80

?

Scaling Your Security Program with Semgrep

​

Semgrep: http://semgrep.dev/

Slides: https://bit.ly/2021-Open-Sec-Summit-Semgrep�

72

73 of 80

Exercise! Find calls to exec() in Ruby

  1. Find all calls to exec()
  2. Find exec() calls where the first argument is not a string literal
  3. Find exec() calls with only 1 argument

​

https://semgrep.dev/s/clintgibler:ruby-exec-demo-try

​

​

73

74 of 80

Exercise! Find TLS config with insecure settings

74

75 of 80

Find arbitrary file read in Flask

75

76 of 80

Exercise! Find XSS in ExpressJS

76

77 of 80

Order of API Calls Must be Enforced

77

78 of 80

Exercise! If you call someFunc(), you need to call it at least twice

78

79 of 80

Outline

  1. The power of secure defaults
  2. Semgrep background
  3. Rule writing - the basics
  4. Tackling bug classes in your org
  5. Integrating into CI
  6. Rule writing - Advanced

79

80 of 80

Autofix!

80