File size: 31,273 Bytes
88d205f |
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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Security Scanner Service
This module provides functionality for scanning code for security vulnerabilities.
"""
import os
import subprocess
import logging
import json
import tempfile
import concurrent.futures
from collections import defaultdict
logger = logging.getLogger(__name__)
class SecurityScanner:
"""
Service for scanning code for security vulnerabilities.
"""
def __init__(self):
"""
Initialize the SecurityScanner.
"""
logger.info("Initialized SecurityScanner")
self.scanners = {
'Python': self._scan_python,
'JavaScript': self._scan_javascript,
'TypeScript': self._scan_javascript, # TypeScript uses the same scanner as JavaScript
'Java': self._scan_java,
'Go': self._scan_go,
'Rust': self._scan_rust,
}
def scan_repository(self, repo_path, languages):
"""
Scan a repository for security vulnerabilities in the specified languages using parallel processing.
Args:
repo_path (str): The path to the repository.
languages (list): A list of programming languages to scan.
Returns:
dict: A dictionary containing scan results for each language.
"""
logger.info(f"Scanning repository at {repo_path} for security vulnerabilities in languages: {languages}")
results = {}
# Scan dependencies first (language-agnostic)
results['dependencies'] = self._scan_dependencies(repo_path)
# Define a function to scan a single language
def scan_language(language):
if language in self.scanners:
try:
logger.info(f"Scanning {language} code in {repo_path} for security vulnerabilities")
return language, self.scanners[language](repo_path)
except Exception as e:
logger.error(f"Error scanning {language} code for security vulnerabilities: {e}")
return language, {
'status': 'error',
'error': str(e),
'vulnerabilities': [],
}
else:
logger.warning(f"No security scanner available for {language}")
return language, {
'status': 'not_supported',
'message': f"Security scanning for {language} is not supported yet.",
'vulnerabilities': [],
}
# Use ThreadPoolExecutor to scan languages in parallel
with concurrent.futures.ThreadPoolExecutor(max_workers=min(len(languages), 5)) as executor:
# Submit all language scanning tasks
future_to_language = {executor.submit(scan_language, language): language for language in languages}
# Process results as they complete
for future in concurrent.futures.as_completed(future_to_language):
language = future_to_language[future]
try:
lang, result = future.result()
results[lang] = result
logger.info(f"Completed security scanning for {lang}")
except Exception as e:
logger.error(f"Exception occurred during security scanning of {language}: {e}")
results[language] = {
'status': 'error',
'error': str(e),
'vulnerabilities': [],
}
return results
def _scan_dependencies(self, repo_path):
"""
Scan dependencies for known vulnerabilities.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Dependency scan results.
"""
logger.info(f"Scanning dependencies in {repo_path}")
results = {
'python': self._scan_python_dependencies(repo_path),
'javascript': self._scan_javascript_dependencies(repo_path),
'java': self._scan_java_dependencies(repo_path),
'go': self._scan_go_dependencies(repo_path),
'rust': self._scan_rust_dependencies(repo_path),
}
# Aggregate vulnerabilities
all_vulnerabilities = []
for lang_result in results.values():
all_vulnerabilities.extend(lang_result.get('vulnerabilities', []))
return {
'status': 'success',
'vulnerabilities': all_vulnerabilities,
'vulnerability_count': len(all_vulnerabilities),
'language_results': results,
}
def _scan_python_dependencies(self, repo_path):
"""
Scan Python dependencies for known vulnerabilities using safety.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for Python dependencies.
"""
logger.info(f"Scanning Python dependencies in {repo_path}")
# Find requirements files
requirements_files = []
for root, _, files in os.walk(repo_path):
for file in files:
if file == 'requirements.txt' or file == 'Pipfile' or file == 'Pipfile.lock' or file == 'setup.py':
requirements_files.append(os.path.join(root, file))
if not requirements_files:
return {
'status': 'no_dependencies',
'message': 'No Python dependency files found.',
'vulnerabilities': [],
}
vulnerabilities = []
for req_file in requirements_files:
try:
# Run safety check
cmd = [
'safety',
'check',
'--file', req_file,
'--json',
]
process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
)
# Parse safety output
if process.stdout.strip():
try:
safety_results = json.loads(process.stdout)
for vuln in safety_results.get('vulnerabilities', []):
vulnerabilities.append({
'package': vuln.get('package_name', ''),
'installed_version': vuln.get('installed_version', ''),
'affected_versions': vuln.get('vulnerable_spec', ''),
'description': vuln.get('advisory', ''),
'severity': vuln.get('severity', ''),
'file': req_file,
'language': 'Python',
})
except json.JSONDecodeError:
logger.error(f"Error parsing safety output: {process.stdout}")
except Exception as e:
logger.error(f"Error running safety on {req_file}: {e}")
return {
'status': 'success',
'vulnerabilities': vulnerabilities,
'vulnerability_count': len(vulnerabilities),
'files_scanned': requirements_files,
}
def _scan_javascript_dependencies(self, repo_path):
"""
Scan JavaScript/TypeScript dependencies for known vulnerabilities using npm audit.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for JavaScript dependencies.
"""
logger.info(f"Scanning JavaScript dependencies in {repo_path}")
# Find package.json files
package_files = []
for root, _, files in os.walk(repo_path):
if 'package.json' in files:
package_files.append(os.path.join(root, 'package.json'))
if not package_files:
return {
'status': 'no_dependencies',
'message': 'No JavaScript dependency files found.',
'vulnerabilities': [],
}
vulnerabilities = []
for pkg_file in package_files:
pkg_dir = os.path.dirname(pkg_file)
try:
# Run npm audit
cmd = [
'npm',
'audit',
'--json',
]
process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
cwd=pkg_dir, # Run in the directory containing package.json
)
# Parse npm audit output
if process.stdout.strip():
try:
audit_results = json.loads(process.stdout)
# Extract vulnerabilities from npm audit results
for vuln_id, vuln_info in audit_results.get('vulnerabilities', {}).items():
vulnerabilities.append({
'package': vuln_info.get('name', ''),
'installed_version': vuln_info.get('version', ''),
'affected_versions': vuln_info.get('range', ''),
'description': vuln_info.get('overview', ''),
'severity': vuln_info.get('severity', ''),
'file': pkg_file,
'language': 'JavaScript',
'cwe': vuln_info.get('cwe', ''),
'recommendation': vuln_info.get('recommendation', ''),
})
except json.JSONDecodeError:
logger.error(f"Error parsing npm audit output: {process.stdout}")
except Exception as e:
logger.error(f"Error running npm audit on {pkg_file}: {e}")
return {
'status': 'success',
'vulnerabilities': vulnerabilities,
'vulnerability_count': len(vulnerabilities),
'files_scanned': package_files,
}
def _scan_java_dependencies(self, repo_path):
"""
Scan Java dependencies for known vulnerabilities.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for Java dependencies.
"""
logger.info(f"Scanning Java dependencies in {repo_path}")
# Find pom.xml or build.gradle files
dependency_files = []
for root, _, files in os.walk(repo_path):
for file in files:
if file == 'pom.xml' or file == 'build.gradle':
dependency_files.append(os.path.join(root, file))
if not dependency_files:
return {
'status': 'no_dependencies',
'message': 'No Java dependency files found.',
'vulnerabilities': [],
}
# For now, we'll just return a placeholder since we don't have a direct tool
# In a real implementation, you might use OWASP Dependency Check or similar
return {
'status': 'not_implemented',
'message': 'Java dependency scanning is not fully implemented yet.',
'vulnerabilities': [],
'files_scanned': dependency_files,
}
def _scan_go_dependencies(self, repo_path):
"""
Scan Go dependencies for known vulnerabilities using govulncheck.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for Go dependencies.
"""
logger.info(f"Scanning Go dependencies in {repo_path}")
# Check if go.mod exists
go_mod_path = os.path.join(repo_path, 'go.mod')
if not os.path.exists(go_mod_path):
return {
'status': 'no_dependencies',
'message': 'No Go dependency files found.',
'vulnerabilities': [],
}
try:
# Run govulncheck
cmd = [
'govulncheck',
'-json',
'./...',
]
process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
cwd=repo_path, # Run in the repository directory
)
# Parse govulncheck output
vulnerabilities = []
if process.stdout.strip():
for line in process.stdout.splitlines():
try:
result = json.loads(line)
if 'vulnerability' in result:
vuln = result['vulnerability']
vulnerabilities.append({
'package': vuln.get('package', ''),
'description': vuln.get('details', ''),
'severity': 'high', # govulncheck doesn't provide severity
'file': go_mod_path,
'language': 'Go',
'cve': vuln.get('osv', {}).get('id', ''),
'affected_versions': vuln.get('osv', {}).get('affected', ''),
})
except json.JSONDecodeError:
continue
return {
'status': 'success',
'vulnerabilities': vulnerabilities,
'vulnerability_count': len(vulnerabilities),
'files_scanned': [go_mod_path],
}
except Exception as e:
logger.error(f"Error running govulncheck: {e}")
return {
'status': 'error',
'error': str(e),
'vulnerabilities': [],
}
def _scan_rust_dependencies(self, repo_path):
"""
Scan Rust dependencies for known vulnerabilities using cargo-audit.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for Rust dependencies.
"""
logger.info(f"Scanning Rust dependencies in {repo_path}")
# Check if Cargo.toml exists
cargo_toml_path = os.path.join(repo_path, 'Cargo.toml')
if not os.path.exists(cargo_toml_path):
return {
'status': 'no_dependencies',
'message': 'No Rust dependency files found.',
'vulnerabilities': [],
}
try:
# Run cargo-audit
cmd = [
'cargo',
'audit',
'--json',
]
process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
cwd=repo_path, # Run in the repository directory
)
# Parse cargo-audit output
vulnerabilities = []
if process.stdout.strip():
try:
audit_results = json.loads(process.stdout)
for vuln in audit_results.get('vulnerabilities', {}).get('list', []):
vulnerabilities.append({
'package': vuln.get('package', {}).get('name', ''),
'installed_version': vuln.get('package', {}).get('version', ''),
'description': vuln.get('advisory', {}).get('description', ''),
'severity': vuln.get('advisory', {}).get('severity', ''),
'file': cargo_toml_path,
'language': 'Rust',
'cve': vuln.get('advisory', {}).get('id', ''),
})
except json.JSONDecodeError:
logger.error(f"Error parsing cargo-audit output: {process.stdout}")
return {
'status': 'success',
'vulnerabilities': vulnerabilities,
'vulnerability_count': len(vulnerabilities),
'files_scanned': [cargo_toml_path],
}
except Exception as e:
logger.error(f"Error running cargo-audit: {e}")
return {
'status': 'error',
'error': str(e),
'vulnerabilities': [],
}
def _scan_python(self, repo_path):
"""
Scan Python code for security vulnerabilities using bandit.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for Python code.
"""
logger.info(f"Scanning Python code in {repo_path} for security vulnerabilities")
# Find Python files
python_files = []
for root, _, files in os.walk(repo_path):
for file in files:
if file.endswith('.py'):
python_files.append(os.path.join(root, file))
if not python_files:
return {
'status': 'no_files',
'message': 'No Python files found in the repository.',
'vulnerabilities': [],
}
try:
# Run bandit
cmd = [
'bandit',
'-r',
'-f', 'json',
repo_path,
]
process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
)
# Parse bandit output
vulnerabilities = []
if process.stdout.strip():
try:
bandit_results = json.loads(process.stdout)
for result in bandit_results.get('results', []):
vulnerabilities.append({
'file': result.get('filename', ''),
'line': result.get('line_number', 0),
'code': result.get('code', ''),
'issue': result.get('issue_text', ''),
'severity': result.get('issue_severity', ''),
'confidence': result.get('issue_confidence', ''),
'cwe': result.get('cwe', ''),
'test_id': result.get('test_id', ''),
'test_name': result.get('test_name', ''),
'language': 'Python',
})
except json.JSONDecodeError:
logger.error(f"Error parsing bandit output: {process.stdout}")
# Group vulnerabilities by severity
vulns_by_severity = defaultdict(list)
for vuln in vulnerabilities:
severity = vuln.get('severity', 'unknown')
vulns_by_severity[severity].append(vuln)
return {
'status': 'success',
'vulnerabilities': vulnerabilities,
'vulnerabilities_by_severity': dict(vulns_by_severity),
'vulnerability_count': len(vulnerabilities),
'files_scanned': len(python_files),
}
except Exception as e:
logger.error(f"Error running bandit: {e}")
return {
'status': 'error',
'error': str(e),
'vulnerabilities': [],
}
def _scan_javascript(self, repo_path):
"""
Scan JavaScript/TypeScript code for security vulnerabilities using NodeJSScan.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for JavaScript/TypeScript code.
"""
logger.info(f"Scanning JavaScript/TypeScript code in {repo_path} for security vulnerabilities")
# Find JavaScript/TypeScript files
js_files = []
for root, _, files in os.walk(repo_path):
if 'node_modules' in root:
continue
for file in files:
if file.endswith(('.js', '.jsx', '.ts', '.tsx')):
js_files.append(os.path.join(root, file))
if not js_files:
return {
'status': 'no_files',
'message': 'No JavaScript/TypeScript files found in the repository.',
'vulnerabilities': [],
}
# For now, we'll use a simplified approach since NodeJSScan might not be available
# In a real implementation, you might use NodeJSScan or similar
# Create a temporary ESLint configuration file with security rules
eslint_config = {
"env": {
"browser": True,
"es2021": True,
"node": True
},
"extends": [
"eslint:recommended",
"plugin:security/recommended"
],
"plugins": [
"security"
],
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module",
"ecmaFeatures": {
"jsx": True
}
},
"rules": {}
}
with tempfile.NamedTemporaryFile(suffix='.json', delete=False) as temp_config:
json.dump(eslint_config, temp_config)
temp_config_path = temp_config.name
try:
# Run ESLint with security plugin
cmd = [
'npx',
'eslint',
'--config', temp_config_path,
'--format', 'json',
'--plugin', 'security',
] + js_files
process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
)
# Parse ESLint output
vulnerabilities = []
if process.stdout.strip():
try:
eslint_results = json.loads(process.stdout)
for result in eslint_results:
file_path = result.get('filePath', '')
for message in result.get('messages', []):
# Only include security-related issues
rule_id = message.get('ruleId', '')
if rule_id and ('security' in rule_id or 'no-eval' in rule_id or 'no-implied-eval' in rule_id):
vulnerabilities.append({
'file': file_path,
'line': message.get('line', 0),
'column': message.get('column', 0),
'issue': message.get('message', ''),
'severity': 'high' if message.get('severity', 0) == 2 else 'medium',
'rule': rule_id,
'language': 'JavaScript',
})
except json.JSONDecodeError:
logger.error(f"Error parsing ESLint output: {process.stdout}")
# Group vulnerabilities by severity
vulns_by_severity = defaultdict(list)
for vuln in vulnerabilities:
severity = vuln.get('severity', 'unknown')
vulns_by_severity[severity].append(vuln)
return {
'status': 'success',
'vulnerabilities': vulnerabilities,
'vulnerabilities_by_severity': dict(vulns_by_severity),
'vulnerability_count': len(vulnerabilities),
'files_scanned': len(js_files),
}
except Exception as e:
logger.error(f"Error scanning JavaScript/TypeScript code: {e}")
return {
'status': 'error',
'error': str(e),
'vulnerabilities': [],
}
finally:
# Clean up the temporary configuration file
if os.path.exists(temp_config_path):
os.unlink(temp_config_path)
def _scan_java(self, repo_path):
"""
Scan Java code for security vulnerabilities.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for Java code.
"""
logger.info(f"Scanning Java code in {repo_path} for security vulnerabilities")
# Find Java files
java_files = []
for root, _, files in os.walk(repo_path):
for file in files:
if file.endswith('.java'):
java_files.append(os.path.join(root, file))
if not java_files:
return {
'status': 'no_files',
'message': 'No Java files found in the repository.',
'vulnerabilities': [],
}
# For now, we'll just return a placeholder since we don't have a direct tool
# In a real implementation, you might use FindSecBugs or similar
return {
'status': 'not_implemented',
'message': 'Java security scanning is not fully implemented yet.',
'vulnerabilities': [],
'files_scanned': java_files,
}
def _scan_go(self, repo_path):
"""
Scan Go code for security vulnerabilities using gosec.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for Go code.
"""
logger.info(f"Scanning Go code in {repo_path} for security vulnerabilities")
# Find Go files
go_files = []
for root, _, files in os.walk(repo_path):
for file in files:
if file.endswith('.go'):
go_files.append(os.path.join(root, file))
if not go_files:
return {
'status': 'no_files',
'message': 'No Go files found in the repository.',
'vulnerabilities': [],
}
try:
# Run gosec
cmd = [
'gosec',
'-fmt', 'json',
'-quiet',
'./...',
]
process = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=False,
cwd=repo_path, # Run in the repository directory
)
# Parse gosec output
vulnerabilities = []
if process.stdout.strip():
try:
gosec_results = json.loads(process.stdout)
for issue in gosec_results.get('Issues', []):
vulnerabilities.append({
'file': issue.get('file', ''),
'line': issue.get('line', ''),
'code': issue.get('code', ''),
'issue': issue.get('details', ''),
'severity': issue.get('severity', ''),
'confidence': issue.get('confidence', ''),
'cwe': issue.get('cwe', {}).get('ID', ''),
'rule_id': issue.get('rule_id', ''),
'language': 'Go',
})
except json.JSONDecodeError:
logger.error(f"Error parsing gosec output: {process.stdout}")
# Group vulnerabilities by severity
vulns_by_severity = defaultdict(list)
for vuln in vulnerabilities:
severity = vuln.get('severity', 'unknown')
vulns_by_severity[severity].append(vuln)
return {
'status': 'success',
'vulnerabilities': vulnerabilities,
'vulnerabilities_by_severity': dict(vulns_by_severity),
'vulnerability_count': len(vulnerabilities),
'files_scanned': len(go_files),
}
except Exception as e:
logger.error(f"Error running gosec: {e}")
return {
'status': 'error',
'error': str(e),
'vulnerabilities': [],
}
def _scan_rust(self, repo_path):
"""
Scan Rust code for security vulnerabilities.
Args:
repo_path (str): The path to the repository.
Returns:
dict: Scan results for Rust code.
"""
logger.info(f"Scanning Rust code in {repo_path} for security vulnerabilities")
# Find Rust files
rust_files = []
for root, _, files in os.walk(repo_path):
for file in files:
if file.endswith('.rs'):
rust_files.append(os.path.join(root, file))
if not rust_files:
return {
'status': 'no_files',
'message': 'No Rust files found in the repository.',
'vulnerabilities': [],
}
# For now, we'll just return a placeholder since we don't have a direct tool
# In a real implementation, you might use cargo-audit or similar for code scanning
return {
'status': 'not_implemented',
'message': 'Rust security scanning is not fully implemented yet.',
'vulnerabilities': [],
'files_scanned': rust_files,
} |