SQL Injection Testing Guide Using Postman

SQL Injection Testing Guide Using Postman

Table of Contents

  1. Introduction
  2. Setting Up Test Environment
  3. SQL Injection Test Cases
  4. Creating Test Collections
  5. Automation Scripts
  6. Reporting and Analysis
  7. Best Practices
  8. Security Considerations

1. Introduction

1.1 What is SQL Injection Testing?

SQL Injection testing is a security testing technique that identifies vulnerabilities where malicious SQL queries can be inserted into application inputs. Using Postman, we can systematically test these vulnerabilities.

1.2 Prerequisites

  • Postman installation
  • Basic understanding of SQL
  • Test environment setup
  • API endpoints for testing

2. Setting Up Test Environment

2.1 Environment Configuration

{
    "id": "sql_injection_env",
    "name": "SQL Injection Testing",
    "values": [
        {
            "key": "baseUrl",
            "value": "https://api-test.example.com",
            "enabled": true
        },
        {
            "key": "authToken",
            "value": "your-auth-token",
            "enabled": true
        },
        {
            "key": "contentType",
            "value": "application/json",
            "enabled": true
        }
    ]
}        

2.2 Collection Variables

{
    "sqlInjectionPayloads": {
        "basic": [
            "' OR '1'='1",
            "'; DROP TABLE users--",
            "' UNION SELECT * FROM users--",
            "' OR '1'='1' --",
            "admin' --"
        ],
        "advanced": [
            "' UNION SELECT NULL,NULL,NULL FROM DUAL--",
            "' HAVING 1=1--",
            "' GROUP BY columnname HAVING 1=1--",
            "' ORDER BY 1--"
        ]
    }
}        

3. SQL Injection Test Cases

3.1 Basic Authentication Bypass

// Test Script for Authentication Bypass
pm.test("SQL Injection Authentication Bypass Test", () => {
    const payloads = [
        {
            "username": "' OR '1'='1",
            "password": "' OR '1'='1"
        },
        {
            "username": "admin'--",
            "password": "anything"
        }
    ];

    payloads.forEach(payload => {
        pm.sendRequest({
            url: pm.environment.get("baseUrl") + "/login",
            method: "POST",
            header: {
                "Content-Type": "application/json"
            },
            body: {
                mode: "raw",
                raw: JSON.stringify(payload)
            }
        }, (error, response) => {
            if (error) {
                console.log(error);
            } else {
                pm.test(`Payload: ${JSON.stringify(payload)}`, () => {
                    pm.expect(response.code).to.not.equal(200);
                });
            }
        });
    });
});        

3.2 Data Extraction Tests

const extractionPayloads = [
    "' UNION SELECT username, password FROM users--",
    "' UNION SELECT table_name, NULL FROM information_schema.tables--",
    "' UNION SELECT column_name, NULL FROM information_schema.columns WHERE table_name='users'--"
];

pm.test("SQL Injection Data Extraction Test", () => {
    extractionPayloads.forEach(payload => {
        // Test implementation for each payload
        testDataExtraction(payload);
    });
});

function testDataExtraction(payload) {
    const request = {
        url: pm.environment.get("baseUrl") + "/api/data?id=" + payload,
        method: "GET",
        header: {
            "Authorization": pm.environment.get("authToken")
        }
    };
    
    pm.sendRequest(request, (error, response) => {
        if (error) {
            console.error(error);
        } else {
            validateResponse(response);
        }
    });
}        

3.3 Blind SQL Injection Tests

const blindPayloads = [
    {
        payload: "' AND SLEEP(5)--",
        type: "time-based"
    },
    {
        payload: "' AND (SELECT CASE WHEN (1=1) THEN 1 ELSE 1*(SELECT 1 UNION SELECT 2) END)--",
        type: "boolean-based"
    }
];

pm.test("Blind SQL Injection Test", () => {
    blindPayloads.forEach(test => {
        testBlindInjection(test);
    });
});

function testBlindInjection(test) {
    const startTime = Date.now();
    
    pm.sendRequest({
        url: pm.environment.get("baseUrl") + "/api/data",
        method: "POST",
        header: {
            "Content-Type": "application/json",
            "Authorization": pm.environment.get("authToken")
        },
        body: {
            mode: "raw",
            raw: JSON.stringify({ query: test.payload })
        }
    }, (error, response) => {
        const endTime = Date.now();
        const duration = endTime - startTime;
        
        if (test.type === "time-based") {
            pm.test(`Time-based blind injection: ${test.payload}`, () => {
                pm.expect(duration).to.be.below(5000);
            });
        }
    });
}        

4. Creating Test Collections

4.1 Collection Structure

{
    "info": {
        "name": "SQL Injection Tests",
        "description": "Comprehensive SQL injection test suite"
    },
    "folders": [
        {
            "name": "Authentication Tests",
            "description": "Tests for authentication bypass attempts"
        },
        {
            "name": "Data Extraction Tests",
            "description": "Tests for unauthorized data extraction"
        },
        {
            "name": "Blind Injection Tests",
            "description": "Time-based and boolean-based tests"
        }
    ]
}        

4.2 Pre-request Scripts

// Global pre-request script for SQL injection tests
pm.variables.set("currentTimestamp", new Date().getTime());

// Load test payloads
const payloads = pm.environment.get("sqlInjectionPayloads");
pm.variables.set("currentPayload", payloads[pm.info.iteration % payloads.length]);

// Setup request logging
console.log(`Testing payload: ${pm.variables.get("currentPayload")}`);        

5. Automation Scripts

5.1 Newman Integration


const newman = require('newman');

newman.run({
    collection: require('./sql-injection-tests.postman_collection.json'),
    environment: require('./test-environment.postman_environment.json'),
    reporters: ['cli', 'htmlextra'],
    iterationCount: 1,
    reporter: {
        htmlextra: {
            export: './reports/sql-injection-report.html',
            template: 'template.hbs'
        }
    }
}, function (err) {
    if (err) { throw err; }
    console.log('Collection run completed!');
});        

5.2 CI/CD Integration


# GitHub Actions workflow example
name: SQL Injection Tests
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Install Newman
      run: npm install -g newman newman-reporter-htmlextra
    - name: Run Tests
      run: |
        newman run collection.json \
          -e environment.json \
          -r cli,htmlextra \
          --reporter-htmlextra-export ./reports/report.html        

6. Reporting and Analysis

6.1 Test Report Structure


const reportTemplate = {
    testSuite: "SQL Injection Tests",
    timestamp: new Date().toISOString(),
    results: {
        total: 0,
        passed: 0,
        failed: 0,
        skipped: 0
    },
    vulnerabilities: [],
    duration: 0
};

function generateReport(results) {
    const report = {...reportTemplate};
    report.results.total = results.length;
    report.results.passed = results.filter(r => r.passed).length;
    report.results.failed = results.filter(r => !r.passed).length;
    
    results.forEach(result => {
        if (!result.passed) {
            report.vulnerabilities.push({
                endpoint: result.endpoint,
                payload: result.payload,
                response: result.response
            });
        }
    });
    
    return report;
}        

6.2 Vulnerability Assessment


function assessVulnerability(testResult) {
    return {
        severity: calculateSeverity(testResult),
        impact: assessImpact(testResult),
        remediation: suggestRemediation(testResult)
    };
}

function calculateSeverity(testResult) {
    // Severity calculation logic
    let severity = 0;
    if (testResult.dataExposed) severity += 3;
    if (testResult.authenticationBypassed) severity += 4;
    if (testResult.databaseModified) severity += 5;
    return severity;
}        

7. Best Practices

7.1 Test Organization

  1. Group similar tests together
  2. Use clear naming conventions
  3. Document test cases
  4. Maintain payload libraries
  5. Regular updates to test cases

7.2 Security Considerations

  1. Use isolated test environments
  2. Avoid testing on production
  3. Secure test credentials
  4. Monitor test execution
  5. Regular security updates

8. Security Considerations

8.1 Safe Testing Guidelines


const safeTestingConfig = {
    maxRequestsPerSecond: 10,
    maxConcurrentRequests: 5,
    timeoutMs: 5000,
    retryAttempts: 3,
    safeModeEnabled: true
};

function validateTestingSafety(request) {
    // Safety validation logic
    return {
        isSafe: true,
        warnings: [],
        recommendations: []
    };
}        

8.2 Environment Protection


const environmentProtection = {
    allowedEnvironments: ['dev', 'test'],
    restrictedEndpoints: ['/admin', '/system'],
    maxPayloadSize: 1024,
    rateLimiting: {
        enabled: true,
        maxRequests: 100,
        timeWindow: 60000
    }
};        



Follow Guneet Singh for more QA Topics




Dushan Anuradha

Automation Test Engineer | Cypress | Playwright | API & CI/CD | AI-Powered Testing | AWS | DevOps | Passionate about Software Quality | MSc in Computer Science

1 个月

Very informative

回复
Anirban Bhattacharjee

QA|Functional Testing |Manual Testing - API, UI, Mobile App| 1X SaFe |2X Scrum.org |2X ISTQB |2X Microfocus |1X IIBF| Domain - LSHC, Investment Banking, Cards etc

1 个月

Love this

回复

"Great insights! It's true that most Manual QA professionals tend to overlook security testing, assuming it's solely the responsibility of penetration testers. Guneet Singh

UPENDRA VENKATA AKHIL MEESALA

Software Developer Engineer in Testing @ Zensar Technologies | Java, Selenium, TestNG, Appium, Cucumber, Rest Assured

2 个月

Good point!

90 percent ka number hawa se nikal leta hun aur jaldi jaldi post kar deta hun reach milega Tiktok ke sab yahan aa gaye kya ?

要查看或添加评论,请登录

Guneet Singh的更多文章

社区洞察

其他会员也浏览了