Dockerfile Security Best Practices with Semgrep

Cenk Kalpakoğlu25 Aug 2022
rules:
- id: use-distroless-base-image
  languages:
    - dockerfile
  message: >-
    Distroless base image not found. Please use `gcr.io/distroless/static-debian10` as a base image.
  severity: ERROR
  metadata:
    category: security
    technology:
      - dockerfile
  patterns:
    - pattern-regex: FR\w+\s[a-zA-Z0-9]\w+\:+\w+
    - pattern-not: FROM gcr.io/distroless/static-debian10
    - pattern-not-regex: \s*\#.*
    - pattern-not-inside: FROM $IMAGE:$TAG as builder
  paths:
    exclude:
      - "./vendor/*"
rules:
  - id: missing-user
    languages:
      - dockerfile
    message:
      By not specifying a USER, a program in the container may run as 'root'. This is a security hazard. If an attacker
      can control a process running as root, they may have control over the container. Ensure that the last USER in a Dockerfile
      is a USER other than 'root'.
    severity: ERROR
    metadata:
      category: security
      technology:
        - dockerfile
      confidence: MEDIUM
    patterns:
      - pattern-either:
          - pattern: CMD ...
          - pattern: ENTRYPOINT ...
      - pattern-not-inside: |
          USER $USER
          ...
rules:
  - id: last-user-is-root
    languages:
      - dockerfile
    message: >-
      The last user in the container is 'root'. This is a security
      hazard because if an attacker gains control of the container
      they will have root access. Switch back to another user after
      running commands as 'root'.
    severity: ERROR
    metadata:
      source-rule-url: https://github.com/hadolint/hadolint/wiki/DL3002
      references:
        - https://github.com/hadolint/hadolint/wiki/DL3002
      category: security
      technology:
        - dockerfile
      confidence: MEDIUM
    patterns:
      - pattern: USER root
      - pattern-not-inside: |
          USER root
          ...
          USER $USER
    paths:
      exclude:
        - "./vendor/*"
rules:
  - id: multistage-build
    languages:
      - dockerfile
    message: >-
      Missing multistage builds.
    severity: INFO
    metadata:
      category: best-practice
      technology:
        - dockerfile
    patterns:
      - pattern: |
          FROM $STAGE AS builder
          ...
      - pattern-not-inside: |
          FROM $STAGE AS builder
          ...
          FROM $IMAGE
          ...
    paths:
      exclude:
        - "./vendor/*"
rules:
  - id: missing-healthcheck
    languages:
      - dockerfile
    message: >-
      Missing HEALTHCHECK instruction.
    severity: INFO
    metadata:
      category: best-practice
      technology:
        - dockerfile
    patterns:
      - pattern: |
         FROM gcr.io/distroless/static-debian10
         ...
      - pattern-not-inside: |
         FROM gcr.io/distroless/static-debian10
         ...
         HEALTHCHECK $F 
         ...
    paths:
      exclude:
        - "./vendor/*"

Get A Demo