Logo Py Security

Py Security

Cộng đồng
l-mb
py-security

Security vulnerability detection and remediation for Python codebases. Identifies SQL injection, hardcoded secrets, weak cryptography, and other OWASP vulnerabilities.

Add to TypingMind

Tổng quan

Nhà phát hànhl-mb
Kho mãpython-refactoring-skills
Tên kỹ năngpy-security
Sao
57
Bản fork
1
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được l-mb công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Py Security trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/l-mb/python-refactoring-skills/tree/main/skills/py-security
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/l-mb/python-refactoring-skills.git /tmp/python-refactoring-skills
mkdir -p .claude/skills
cp -r /tmp/python-refactoring-skills/skills/py-security .claude/skills/py-security
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Py Security trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Py Security ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Py Security với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Python Security Analysis and Remediation

Find and fix security vulnerabilities in Python code following Engineering Charter security principles.

Objectives

  1. Detect security vulnerabilities using automated scanners
  2. Identify SQL injection risks
  3. Find hardcoded secrets and credentials
  4. Detect weak cryptographic practices
  5. Fix vulnerabilities following secure coding patterns
  6. Prevent secrets from being committed to git

Required Tools

Add to [dependency-groups] dev: "bandit", "ruff"

  • bandit: AST-based security scanner
  • ruff --select S: Built-in Bandit rules (faster alternative)

Permissions: Run py-quality-setup first to configure .claude/settings.local.json with all needed tool permissions.

Discovery Phase

Run Security Scanners

bash
# Using bandit (comprehensive reports)
bandit -r . -f json -o bandit_report.json
bandit -r . -ll  # Show only medium/high severity

# Using ruff (faster, integrates with existing tooling)
ruff check . --select S
ruff check . --select S --output-format=json > security_report.json

Common Vulnerability Categories

High severity (fix immediately):

  • S608: SQL injection via string formatting
  • S105, S106, S107: Hardcoded passwords, secrets, keys
  • S501, S506: Weak SSL/TLS configuration
  • S324: Insecure hash functions (MD5, SHA1)
  • S602, S603, S604, S605, S606, S607: Shell injection risks

Medium severity:

  • S311: Insecure random number generation
  • S301, S302, S303: Insecure deserialization (pickle)
  • S701, S702: Jinja2 autoescape issues

Low severity (consider context):

  • S101: Use of assert (disabled in production)
  • S104: Binding to all interfaces (0.0.0.0)

Remediation Patterns

SQL Injection Prevention

python
# BEFORE - Vulnerable to SQL injection
def get_user(user_id: str) -> dict:
    cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
    return cursor.fetchone()

# AFTER - Use parametrized queries
def get_user(user_id: str) -> dict:
    cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
    return cursor.fetchone()

# For dynamic table/column names (cannot be parametrized)
from psycopg2 import sql

def get_data(table_name: str, column: str) -> list:
    # Validate inputs first!
    allowed_tables = {"users", "orders", "products"}
    if table_name not in allowed_tables:
        raise ValueError(f"Invalid table: {table_name}")

    query = sql.SQL("SELECT {column} FROM {table}").format(
        column=sql.Identifier(column),
        table=sql.Identifier(table_name)
    )
    cursor.execute(query)
    return cursor.fetchall()

Hardcoded Secrets Removal

python
# BEFORE - Hardcoded secrets (NEVER commit these)
API_KEY = "sk-1234567890abcdef"
DATABASE_URL = "postgres://user:password@localhost/db"
SECRET_TOKEN = "my-secret-token-123"

# AFTER - Use environment variables
import os

API_KEY = os.environ["API_KEY"]  # Raises if not set
DATABASE_URL = os.getenv("DATABASE_URL", "postgres://localhost/db")  # With default
SECRET_TOKEN = os.environ.get("SECRET_TOKEN")  # Returns None if not set

# For development, use python-dotenv
from dotenv import load_dotenv
load_dotenv()  # Loads from .env file (add .env to .gitignore!)
API_KEY = os.environ["API_KEY"]

Secure Random Number Generation

python
# BEFORE - Insecure for security-sensitive operations
import random

session_token = random.randint(100000, 999999)
api_key = ''.join(random.choices('abcdef0123456789', k=32))

# AFTER - Use secrets module for cryptographic randomness
import secrets

session_token = secrets.randbelow(900000) + 100000
api_key = secrets.token_hex(16)  # 32 hex characters
secure_password = secrets.token_urlsafe(32)  # URL-safe token

Secure Cryptography

python
# BEFORE - Weak hash functions
import hashlib

password_hash = hashlib.md5(password.encode()).hexdigest()  # Weak!
checksum = hashlib.sha1(data).hexdigest()  # Weak for security!

# AFTER - Use strong hash functions
import hashlib

# For passwords - use bcrypt or argon2
from argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
ph.verify(password_hash, password)  # Verify

# For data integrity - use SHA256 or better
checksum = hashlib.sha256(data).hexdigest()
secure_hash = hashlib.blake2b(data).hexdigest()

Shell Command Injection Prevention

python
# BEFORE - Shell injection vulnerability
import os
import subprocess

filename = user_input
os.system(f"cat {filename}")  # Dangerous!
subprocess.call(f"ls {directory}", shell=True)  # Dangerous!

# AFTER - Use subprocess with list arguments (no shell)
import subprocess
from pathlib import Path

# Validate input first
filename = user_input
if not Path(filename).exists():
    raise ValueError("File not found")

# Use list form, no shell=True
subprocess.run(["cat", filename], check=True)
subprocess.run(["ls", directory], check=True)

# Even better - use Python libraries instead of shell commands
with open(filename) as f:
    content = f.read()

Git Hooks Integration

Add secret detection to git hooks (complement to py-git-hooks):

bash
# In .git/hooks/pre-commit, add before other checks:

# Detect potential secrets
if git diff --cached | grep -qiE '(password|secret|api[_-]?key|token|credentials)'; then
    echo "⚠️  Warning: Potential secrets detected in staged changes"
    echo "Review carefully before committing"
    read -p "Continue? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

Verification Checklist

  • ruff check . --select S reports no security issues
  • bandit -r . -ll reports no medium/high severity issues
  • No hardcoded secrets in codebase (grep for password, secret, api_key, token)
  • Secrets loaded from environment variables or .env file
  • .env file is in .gitignore
  • All SQL queries use parametrized queries
  • All tests pass after security fixes

Examples

Example: Security audit workflow

1. Scan: ruff check . --select S; bandit -r . -ll
2. Found: SQL injection (S608), hardcoded secret (S105)
3. Fix SQL: Use parametrized query with %s placeholders
4. Fix secret: Move to .env, use os.environ["API_KEY"]
5. Verify: Scans clean, tests pass

Related Skills

  • Prerequisites: py-quality-setup (configure ruff for security checks)
  • Enforcement: py-git-hooks (add security scanning to pre-commit)
  • See also: py-code-health (cleanup after security fixes)

Câu hỏi thường gặp

Kỹ năng AI Py Security làm được gì?

Security vulnerability detection and remediation for Python codebases. Identifies SQL injection, hardcoded secrets, weak cryptography, and other OWASP vulnerabilities.

Vì sao nên dùng Py Security trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Py Security là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Py Security trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/l-mb/python-refactoring-skills/tree/main/skills/py-security. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Py Security?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Py Security với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Py Security với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Py Security có miễn phí không?

Có. Kỹ năng này được l-mb phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇