Rust Secure Coding

Secure coding practices for Rust applications.


SQL Injection Prevention

 1// ❌ Vulnerable
 2let username = req.param("username");
 3let query = format!("SELECT * FROM users WHERE username = '{}'", username);
 4conn.query(&query);
 5
 6// βœ… Secure (using sqlx)
 7let username = req.param("username");
 8let user = sqlx::query_as!(User, "SELECT * FROM users WHERE username = $1", username)
 9    .fetch_one(&pool)
10    .await?;

Command Injection Prevention

 1// ❌ Vulnerable
 2use std::process::Command;
 3let filename = req.param("file");
 4let output = Command::new("sh")
 5    .arg("-c")
 6    .arg(format!("cat {}", filename))
 7    .output()?;
 8
 9// βœ… Secure
10use std::process::Command;
11let filename = req.param("file");
12if !filename.chars().all(|c| c.is_alphanumeric() || c == '.' || c == '_') {
13    return Err(Error::InvalidFilename);
14}
15let output = Command::new("cat")
16    .arg(filename)
17    .output()?;

Secure Password Hashing

 1// ❌ Insecure
 2use md5::{Md5, Digest};
 3let hash = Md5::digest(password.as_bytes());
 4
 5// βœ… Secure
 6use argon2::{
 7    password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
 8    Argon2
 9};
10
11let salt = SaltString::generate(&mut OsRng);
12let argon2 = Argon2::default();
13let password_hash = argon2.hash_password(password.as_bytes(), &salt)?
14    .to_string();
15
16// Verify
17let parsed_hash = PasswordHash::new(&password_hash)?;
18argon2.verify_password(password.as_bytes(), &parsed_hash)?;

Secure Random Generation

 1// ❌ Insecure
 2use rand::Rng;
 3let mut rng = rand::thread_rng();
 4let token: u32 = rng.gen();
 5
 6// βœ… Secure
 7use rand::rngs::OsRng;
 8use rand::RngCore;
 9
10let mut token = [0u8; 32];
11OsRng.fill_bytes(&mut token);

Unsafe Code Review

 1// ❌ Dangerous
 2unsafe {
 3    let ptr = some_value as *const i32;
 4    *ptr  // Potential UB
 5}
 6
 7// βœ… Better: Minimize unsafe
 8// Only use unsafe when absolutely necessary
 9// Document safety invariants
10/// # Safety
11/// `ptr` must be valid and aligned
12unsafe fn read_value(ptr: *const i32) -> i32 {
13    ptr.read()
14}

Related Snippets

  • C/C++ Code Smells
    Common code smells in C/C++ and how to fix them. Memory Leaks 1// ❌ Bad 2void …
  • C/C++ Secure Coding
    Secure coding practices for C/C++ applications. Buffer Overflow Prevention 1// ❌ …
  • C/C++ Vulnerability Checks
    Tools for checking vulnerabilities in C/C++ code. Valgrind 1# Install 2sudo apt …
  • Common Antipatterns
    Common software antipatterns to avoid across all languages and architectures. …
  • Common Code Smells
    Common code smells to watch for during code reviews with examples and fixes. …
  • Developer Pre-Submission Checklist
    Comprehensive checklist for developers before submitting a pull request. Code …
  • Go Code Smells
    Common code smells in Go and how to fix them. Ignoring Errors 1// ❌ Bad 2result, …
  • Go Secure Coding
    Secure coding practices for Go applications. SQL Injection Prevention 1// ❌ …
  • Go Vulnerability Checks
    Tools for checking vulnerabilities in Go code. Govulncheck 1# Install 2go …
  • Haskell Code Smells
    Common code smells in Haskell and how to fix them. Partial Functions 1-- ❌ Bad: …
  • Haskell Secure Coding
    Secure coding practices for Haskell applications. SQL Injection Prevention 1-- ❌ …
  • Haskell Vulnerability Checks
    Tools for checking vulnerabilities in Haskell code. Cabal Outdated 1# Check …
  • Python Code Smells
    Common code smells in Python and how to fix them. Mutable Default Arguments 1# ❌ …
  • Python Secure Coding
    Secure coding practices for Python applications. SQL Injection Prevention 1# ❌ …
  • Python Vulnerability Checks
    Tools for checking vulnerabilities in Python code. Safety - Dependency Scanner …
  • Reviewer Checklist
    Comprehensive checklist for code reviewers to ensure thorough and constructive …
  • Rust Code Smells
    Common code smells in Rust and how to fix them. Unwrap/Expect Abuse 1// ❌ Bad …
  • Rust Vulnerability Checks
    Tools for checking vulnerabilities in Rust code. Cargo Audit 1# Install 2cargo …
  • TypeScript Code Smells
    Common code smells in TypeScript and how to fix them. Using any 1// ❌ Bad …
  • TypeScript Secure Coding
    Secure coding practices for TypeScript applications. XSS Prevention 1// ❌ …
  • TypeScript Vulnerability Checks
    Tools for checking vulnerabilities in TypeScript/JavaScript code. npm audit 1# …