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.

rulesinsecure-deserialization.md

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

Prevent Insecure Deserialization

Insecure deserialization occurs when untrusted data is used to abuse the logic of an application, inflict denial of service attacks, or execute arbitrary code. Objects can be serialized into strings and later loaded from strings, but deserialization of untrusted data can lead to remote code execution (RCE). Never deserialize data from untrusted sources. Use safer alternatives like JSON for data interchange.


Language: Python

Pickle Deserialization

Incorrect (using pickle with user input):

import pickle
from base64 import b64decode
from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    user_obj = request.cookies.get('uuid')
    return "Hey there! {}!".format(pickle.loads(b64decode(user_obj)))

Correct (use JSON or load from trusted file):

import pickle
import json

@app.route("/ok")
def ok():
    # Load from trusted local file
    data = pickle.load(open('./config/settings.dat', "rb"))

    # Or use JSON for untrusted data
    user_data = json.loads(request.data)
    return user_data

References:


Language: JavaScript / TypeScript

Object Deserialization

Incorrect (using insecure deserialization libraries):

var node_serialize = require("node-serialize")

module.exports.handler = function (req, res) {
    var data = req.files.products.data.toString('utf8')
    node_serialize.unserialize(data)
}

Correct (use JSON.parse for untrusted data):

module.exports.handler = function (req, res) {
    var data = req.body.toString('utf8')
    var parsed = JSON.parse(data)
    return parsed
}

References:


Language: Java

ObjectInputStream Deserialization

Incorrect (using ObjectInputStream to deserialize untrusted data):

import java.io.InputStream;
import java.io.ObjectInputStream;

public class Deserializer {
    public Object deserializeObject(InputStream receivedData) throws Exception {
        ObjectInputStream in = new ObjectInputStream(receivedData);
        return in.readObject();
    }
}

Correct (use JSON or implement input validation):

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;

public class SafeDeserializer {
    public MyClass deserialize(InputStream data) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(data, MyClass.class);
    }
}

References:


Language: Ruby

Marshal/YAML Deserialization

Incorrect (using Marshal.load or YAML.load with user input):

def bad_deserialization
    data = params['data']
    obj = Marshal.load(data)

    yaml_data = params['yaml']
    config = YAML.load(yaml_data)
end

Correct (use safe options or trusted data):

def ok_deserialization
    # Use YAML.safe_load for untrusted data
    config = YAML.safe_load(params['yaml'])

    # Load from trusted file
    obj = YAML.load(File.read("config.yml"))

    # Use JSON for untrusted data
    data = JSON.parse(params['data'])
end

References:


Language: C#

BinaryFormatter Deserialization

Incorrect (using BinaryFormatter which is inherently insecure):

using System.Runtime.Serialization.Formatters.Binary;

public class InsecureDeserialization {
    public void Deserialize(string data) {
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(data));
        object obj = formatter.Deserialize(stream);
    }
}

Correct (use System.Text.Json or Newtonsoft with safe settings):

using System.Text.Json;

public class SafeDeserialization {
    public MyClass Deserialize(string json) {
        return JsonSerializer.Deserialize<MyClass>(json);
    }
}

References:


Language: PHP

unserialize() with User Input

Incorrect (unserializing user-controlled data):

<?php
$data = $_GET["data"];
$object = unserialize($data);

Correct (use JSON or hardcoded data):

<?php
// Use json_decode for untrusted data
$object = json_decode($_GET["data"], true);

// Or use unserialize only with hardcoded strings
$object = unserialize('O:1:"a":1:{s:5:"value";s:3:"100";}');

References:


General Prevention Guidelines

  1. Never deserialize untrusted data - Treat all external data as potentially malicious
  2. Use JSON for data interchange - JSON only returns primitive types (strings, arrays, objects, numbers, null)
  3. Implement integrity checks - Use HMACs to sign serialized data to detect tampering
  4. Use allowlists for deserialization - Only allow specific, known-safe classes to be deserialized
  5. Avoid native serialization formats - pickle, Marshal, ObjectInputStream, BinaryFormatter are all dangerous
  6. Use safe YAML loaders - Always use SafeLoader or safe_load with YAML libraries
  7. Monitor and log deserialization - Alert on unexpected deserialization attempts
  8. Keep libraries updated - Apply security patches promptly

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.