All skills
semgrep avatar

/code-security

@327da93 official
by semgrepsemgrep/skills316 stars
31

Security guidelines for writing secure code. Use when writing code, reviewing code for vulnerabilities, or asking about secure coding practices like 'check for SQL injection' or 'review security'. IMPORTANT: Always consult this skill when writing or reviewing any code that handles user input, authentication, file operations, database queries, network requests, cryptography, or infrastructure configuration (Terraform, Kubernetes, Docker, GitHub Actions) — even if the user doesn't explicitly mention security. Also use when users ask to 'review my code', 'check this for bugs', or 'is this safe'.

Use this Skill: https://skilld.dev/gh/semgrep/skills/code-security

This session only. Nothing lands on disk.

rulesrace-condition.md

≈1.8k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Prevent Race Conditions

Race conditions occur when the behavior of software depends on the timing or sequence of events that execute in an unpredictable order. Time-of-check Time-of-use (TOCTOU) vulnerabilities are a specific type of race condition where a resource's state is checked at one point in time but used at a later point, allowing an attacker to modify the resource between the check and use.

Common race condition patterns include:

  • Insecure temporary file creation: Using functions that create predictable filenames, allowing attackers to create symlinks or replace files before they are opened
  • TOCTOU file operations: Checking file existence/permissions then operating on the file, creating a window for manipulation
  • Hardcoded temporary paths: Writing to shared /tmp directories without secure file creation, enabling symlink attacks

Language: OCaml

Insecure Temporary File Creation

Using Filename.temp_file might lead to race conditions since the file could be altered or replaced by a symlink before being opened.

Incorrect (vulnerable to race condition):

(* ruleid:ocamllint-tempfile *)
let ofile = Filename.temp_file "test" "" in
Printf.printf "%s\n" ofile

Correct (use safer alternatives):

(* Use open_temp_file which returns both the filename and an open channel *)
let (filename, oc) = Filename.open_temp_file "test" "" in
Printf.fprintf oc "data\n";
close_out oc

References:


Language: Python

Insecure tempfile.mktemp()

The tempfile.mktemp() function is explicitly marked as unsafe in Python's documentation. The file name returned may not exist when generated, but by the time you attempt to create it, another process may have created a file with that name.

Incorrect (vulnerable to race condition):

import tempfile

# ruleid: tempfile-insecure
x = tempfile.mktemp()
# ruleid: tempfile-insecure
x = tempfile.mktemp(dir="/tmp")

Correct (use secure alternatives):

import os
import tempfile

# Use NamedTemporaryFile which atomically creates and opens the file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    f.write("data")
    filename = f.name

# Or use mkstemp which returns both file descriptor and name
fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, 'w') as f:
        f.write("data")
finally:
    os.unlink(path)

References:


Hardcoded /tmp Path

Using hardcoded paths in shared temporary directories like /tmp is insecure because other users on the system can predict and manipulate these files.

Incorrect (hardcoded tmp path):

def test1():
    # ruleid:hardcoded-tmp-path
    f = open("/tmp/blah.txt", 'w')
    f.write("hello world")
    f.close()

def test2():
    # ruleid:hardcoded-tmp-path
    f = open("/tmp/blah/blahblah/blah.txt", 'r')
    data = f.read()
    f.close()

def test4():
    # ruleid:hardcoded-tmp-path
    with open("/tmp/blah.txt", 'r') as fin:
        data = fin.read()

Correct (use tempfile module or relative paths):

def test3():
    # ok:hardcoded-tmp-path
    f = open("./tmp/blah.txt", 'w')
    f.write("hello world")
    f.close()

def test3a():
    # ok:hardcoded-tmp-path
    f = open("/var/log/something/else/tmp/blah.txt", 'w')
    f.write("hello world")
    f.close()

def test5():
    # ok:hardcoded-tmp-path
    with open("./tmp/blah.txt", 'w') as fout:
        fout.write("hello world")

References:


Language: Go

Insecure Temporary File Creation

Creating files directly in /tmp without using ioutil.TempFile or os.CreateTemp is vulnerable to race conditions and symlink attacks.

Incorrect (hardcoded tmp path):

package samples

import (
	"fmt"
	"io/ioutil"
)

func main() {
	// ruleid:bad-tmp-file-creation
	err := ioutil.WriteFile("/tmp/demo2", []byte("This is some data"), 0644)
	if err != nil {
		fmt.Println("Error while writing!")
	}
}

Correct (use os.CreateTemp for atomic creation):

import "os"

func main_good() {
	// ok:bad-tmp-file-creation
	f, err := os.CreateTemp("", "my_temp-*.txt")
	if err != nil {
		fmt.Println("Error while creating temp file!")
		return
	}
	defer f.Close()

	_, err = f.WriteString("secure data")
	if err != nil {
		fmt.Println("Error while writing!")
	}
}

Note: ioutil.TempFile is deprecated since Go 1.16. Use os.CreateTemp which is a direct replacement. For pre-1.16 code, ioutil.TempFile has the same behavior.

References:


General Best Practices for Avoiding Race Conditions

Temporary File Security

  1. Never use predictable filenames - Always use secure random names
  2. Use atomic file creation - Functions that create and open in one operation
  3. Set restrictive permissions - Use mode 0600 or 0700 for temporary files/directories
  4. Use per-user temporary directories - Consider using $TMPDIR or user-specific paths
  5. Clean up properly - Delete temporary files in a finally block or defer statement

TOCTOU Prevention

  1. Avoid check-then-use patterns - Don't check file existence before opening
  2. Use atomic operations - Prefer operations that check and act atomically
  3. Use file descriptors - Once opened, operate on the descriptor not the path
  4. Lock files when needed - Use advisory or mandatory locks for shared resources

Language-Specific Secure Alternatives

Language Insecure Secure Alternative
Python tempfile.mktemp() tempfile.NamedTemporaryFile(), tempfile.mkstemp()
Go ioutil.WriteFile("/tmp/...") os.CreateTemp() (ioutil.TempFile() is deprecated)
OCaml Filename.temp_file Filename.open_temp_file
C tmpnam(), tempnam() mkstemp(), mkstemps()
Java File.createTempFile() then open Files.createTempFile() with immediate use

References:

Source: SKILL.md on GitHub

2 warnings16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    This skill provides a comprehensive library of security guidelines and code examples to help AI agents write secure code and perform security reviews. It covers OWASP Top 10 vulnerabilities, infrastructure security (Terraform, Kubernetes, Docker), and general best practices. While the files contain examples of vulnerable code (such as SQL injection and hardcoded secrets), these are used exclusively for educational purposes to demonstrate what to avoid and are part of the 'Incorrect' examples within the security rules.

  • Socket16d

    2 alerts: gptSecurity

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer6mo

    4/34 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 327da93. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 7 months ago
  • Security
  • Infrastructure
  • code-review
  • owasp
  • sql-injection
  • xss
  • command-injection
  • authentication
  • terraform
  • kubernetes
  • docker

README badge

README badge for semgrep/skills/code-security

Provides security rules across 15+ languages covering OWASP Top 10 vulnerabilities, infrastructure configuration, and secure coding practices. Includes SQL injection, XSS, command injection, cryptography, and Kubernetes/Terraform security with language-specific priority guidelines and rule files for detailed code examples.

Generated from the current SKILL.md.

Does this skill cover infrastructure security like Terraform and Kubernetes?
Yes. The skill includes 28 rule categories covering Terraform (AWS, Azure, GCP), Kubernetes, Docker, and GitHub Actions alongside language-specific rules for Python, JavaScript, Java, Go, C/C++, Ruby, and PHP.
When should I use this skill — only when the user asks about security?
No. The skill is designed for proactive mode: automatically check for vulnerabilities when writing or reviewing any code that handles user input, authentication, databases, file operations, network requests, cryptography, or infrastructure configuration — even if the user doesn't explicitly mention security.
What vulnerabilities does this skill prioritize?
It prioritizes Critical impact rules first: SQL injection, command injection, XSS, XXE, path traversal, insecure deserialization, code injection, hardcoded secrets, and memory safety. High impact rules include insecure crypto, SSRF, JWT issues, and CSRF.
Does this skill provide code examples for each vulnerability type?
Yes. Each rule category (e.g., `rules/sql-injection.md`) contains detailed vulnerable and secure code examples in the relevant language.

Generated from the current SKILL.md. These answers refresh after source changes.