Cloudflare WAF Rules
Cloudflare WAF Rules
Configure Cloudflare's WAF for SQL injection protection:
// Cloudflare Workers script for custom SQL injection protection
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Parse request
const url = new URL(request.url)
const params = url.searchParams
const body = await request.text()
// SQL injection detection
const sqlInjectionScore = calculateSQLInjectionScore(params, body, request.headers)
if (sqlInjectionScore > 0.8) {
// Block request
return new Response('Access Denied', {
status: 403,
headers: {
'X-Block-Reason': 'SQL-Injection-Detected',
'X-Score': sqlInjectionScore.toString()
}
})
} else if (sqlInjectionScore > 0.5) {
// Challenge with CAPTCHA
return fetch(request, {
cf: {
challengeTimeout: 30,
mirage: true,
polish: 'lossy',
scrapeShield: true
}
})
}
// Pass through clean requests
return fetch(request)
}
function calculateSQLInjectionScore(params, body, headers) {
let score = 0
const suspiciousPatterns = [
/UNION.*SELECT/i,
/OR\s+1\s*=\s*1/i,
/';.*--/,
/EXEC(\s|\()/i,
/DROP\s+TABLE/i
]
// Check all inputs
const inputs = [
...Array.from(params.values()),
body,
headers.get('Referer') || '',
headers.get('User-Agent') || ''
]
inputs.forEach(input => {
suspiciousPatterns.forEach(pattern => {
if (pattern.test(input)) {
score += 0.3
}
})
})
return Math.min(score, 1)
}
Remember that WAFs and security headers are not replacements for secure coding practices. They provide valuable additional protection, but determined attackers can often find ways to bypass WAF rules. Use them as part of a comprehensive security strategy that prioritizes secure code, with WAFs serving as an important but supplementary defense layer.