All skills
semgrep avatar

/code-security

@327da93 official
by semgrepsemgrep/skills317 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.

rulescsrf.md

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

Prevent Cross-Site Request Forgery

Cross-Site Request Forgery (CSRF) is an attack that forces authenticated users to execute unwanted actions on a web application. When a user is authenticated, their browser automatically includes session cookies with requests. Attackers can craft malicious pages that trigger requests to vulnerable applications, causing actions to be performed without the user's consent.


Language: Python / Django

CSRF Exempt Decorator

Incorrect (using @csrf_exempt decorator):

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

Correct (remove csrf_exempt decorator):

from django.http import HttpResponse

def my_view(request):
    return HttpResponse('Hello world')

References:


Language: JavaScript / Express

Missing CSRF Middleware

⚠ Deprecation Notice: The csurf npm package is deprecated and should not be used in new projects. Use a maintained alternative such as csrf-csrf (Double-Submit Cookie pattern) or csrf-sync (Synchronizer Token pattern).

Incorrect (Express app without CSRF protection):

const express = require('express')
const bodyParser = require('body-parser')

const app = express()

app.post('/process', bodyParser.urlencoded({ extended: false }), function(req, res) {
    res.send('data is being processed')
})

Correct — Option A: csrf-csrf (Double-Submit Cookie pattern):

const express = require('express')
const cookieParser = require('cookie-parser')
const { doubleCsrf } = require('csrf-csrf')

const { doubleCsrfProtection, generateToken } = doubleCsrf({
  getSecret: () => process.env.CSRF_SECRET,
  cookieName: '__Host-psifi.x-csrf-token',
  cookieOptions: { sameSite: 'strict', secure: true },
})

const app = express()
app.use(cookieParser())
app.use(doubleCsrfProtection)

// Generate a token for forms/SPA clients
app.get('/csrf-token', (req, res) => {
  res.json({ token: generateToken(req, res) })
})

Correct — Option B: csrf-sync (Synchronizer Token pattern):

const express = require('express')
const { csrfSync } = require('csrf-sync')

const { csrfSynchronisedProtection, generateToken } = csrfSync()

const app = express()
app.use(csrfSynchronisedProtection)

Additional defenses (complement token-based CSRF protection):

  • Set SameSite=Strict or SameSite=Lax on session cookies.
  • Validate Sec-Fetch-Site / Origin headers (Fetch Metadata) to reject cross-origin requests at the edge.

References:


Language: Java / Spring

CSRF Disabled

Incorrect (explicitly disabling CSRF protection):

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated();
    }
}

Correct (CSRF protection enabled by default):

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated();
    }
}

References:


Language: Ruby / Rails

Missing CSRF Protection

Incorrect (controller without protect_from_forgery):

class DangerousController < ActionController::Base
  puts "do more stuff"
end

Correct (controller with protect_from_forgery):

class SafeController < ActionController::Base
  protect_from_forgery with: :exception

  puts "do more stuff"
end

References:


General 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.