flutter-security-analyzer 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flutter_security_analyzer/__init__.py +12 -0
- flutter_security_analyzer/__main__.py +8 -0
- flutter_security_analyzer/core/__init__.py +15 -0
- flutter_security_analyzer/core/config.py +128 -0
- flutter_security_analyzer/core/scanner.py +543 -0
- flutter_security_analyzer/main.py +150 -0
- flutter_security_analyzer/mappers/__init__.py +9 -0
- flutter_security_analyzer/mappers/masvs_mapper.py +308 -0
- flutter_security_analyzer/patterns/__init__.py +32 -0
- flutter_security_analyzer/patterns/auth_patterns.py +95 -0
- flutter_security_analyzer/patterns/base_pattern.py +514 -0
- flutter_security_analyzer/patterns/code_patterns.py +103 -0
- flutter_security_analyzer/patterns/crypto_patterns.py +78 -0
- flutter_security_analyzer/patterns/network_patterns.py +61 -0
- flutter_security_analyzer/patterns/pattern_registry.py +164 -0
- flutter_security_analyzer/patterns/platform_patterns.py +97 -0
- flutter_security_analyzer/patterns/privacy_patterns.py +64 -0
- flutter_security_analyzer/patterns/resilience_patterns.py +68 -0
- flutter_security_analyzer/patterns/storage_patterns.py +111 -0
- flutter_security_analyzer/reporters/__init__.py +11 -0
- flutter_security_analyzer/reporters/console_reporter.py +165 -0
- flutter_security_analyzer/reporters/html_reporter.py +230 -0
- flutter_security_analyzer/reporters/json_reporter.py +107 -0
- flutter_security_analyzer/utils/__init__.py +7 -0
- flutter_security_analyzer-1.0.1.dist-info/METADATA +239 -0
- flutter_security_analyzer-1.0.1.dist-info/RECORD +30 -0
- flutter_security_analyzer-1.0.1.dist-info/WHEEL +5 -0
- flutter_security_analyzer-1.0.1.dist-info/entry_points.txt +2 -0
- flutter_security_analyzer-1.0.1.dist-info/licenses/LICENSE +21 -0
- flutter_security_analyzer-1.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core Scanner Module
|
|
3
|
+
|
|
4
|
+
This module contains the main SecurityScanner class that orchestrates
|
|
5
|
+
the vulnerability detection process.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Dict, List, Set, Union
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
|
|
14
|
+
from flutter_security_analyzer import __version__
|
|
15
|
+
from .config import ScannerConfig
|
|
16
|
+
from flutter_security_analyzer.patterns.pattern_registry import PatternRegistry
|
|
17
|
+
from flutter_security_analyzer.mappers.masvs_mapper import MasvsMapper
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Finding:
|
|
22
|
+
"""Represents a single security finding."""
|
|
23
|
+
vulnerability_id: str
|
|
24
|
+
title: str
|
|
25
|
+
description: str
|
|
26
|
+
severity: str # critical, high, medium, low, info
|
|
27
|
+
file_path: str
|
|
28
|
+
line_number: int
|
|
29
|
+
code_snippet: str
|
|
30
|
+
masvs_category: str
|
|
31
|
+
masvs_control: str
|
|
32
|
+
remediation: str
|
|
33
|
+
cwe_id: str = ""
|
|
34
|
+
confidence: str = "high" # high, medium, low
|
|
35
|
+
|
|
36
|
+
def to_dict(self) -> dict:
|
|
37
|
+
"""Convert finding to dictionary."""
|
|
38
|
+
return {
|
|
39
|
+
'vulnerability_id': self.vulnerability_id,
|
|
40
|
+
'title': self.title,
|
|
41
|
+
'description': self.description,
|
|
42
|
+
'severity': self.severity,
|
|
43
|
+
'file_path': self.file_path,
|
|
44
|
+
'line_number': self.line_number,
|
|
45
|
+
'code_snippet': self.code_snippet,
|
|
46
|
+
'masvs_category': self.masvs_category,
|
|
47
|
+
'masvs_control': self.masvs_control,
|
|
48
|
+
'remediation': self.remediation,
|
|
49
|
+
'cwe_id': self.cwe_id,
|
|
50
|
+
'confidence': self.confidence
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class ScanResults:
|
|
56
|
+
"""Container for scan results."""
|
|
57
|
+
scan_path: str
|
|
58
|
+
scan_timestamp: str
|
|
59
|
+
scanner_version: str
|
|
60
|
+
total_files_scanned: int
|
|
61
|
+
total_lines_scanned: int
|
|
62
|
+
findings: List[Finding] = field(default_factory=list)
|
|
63
|
+
scan_duration_seconds: float = 0.0
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def total_findings(self) -> int:
|
|
67
|
+
return len(self.findings)
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def critical_count(self) -> int:
|
|
71
|
+
return sum(1 for f in self.findings if f.severity == 'critical')
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def high_count(self) -> int:
|
|
75
|
+
return sum(1 for f in self.findings if f.severity == 'high')
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def medium_count(self) -> int:
|
|
79
|
+
return sum(1 for f in self.findings if f.severity == 'medium')
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def low_count(self) -> int:
|
|
83
|
+
return sum(1 for f in self.findings if f.severity == 'low')
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def info_count(self) -> int:
|
|
87
|
+
return sum(1 for f in self.findings if f.severity == 'info')
|
|
88
|
+
|
|
89
|
+
def get_findings_by_category(self, category: str) -> List[Finding]:
|
|
90
|
+
"""Get findings filtered by MASVS category."""
|
|
91
|
+
return [f for f in self.findings if f.masvs_category == category]
|
|
92
|
+
|
|
93
|
+
def get_findings_by_severity(self, severity: str) -> List[Finding]:
|
|
94
|
+
"""Get findings filtered by severity."""
|
|
95
|
+
return [f for f in self.findings if f.severity == severity]
|
|
96
|
+
|
|
97
|
+
def to_dict(self) -> dict:
|
|
98
|
+
"""Convert results to dictionary."""
|
|
99
|
+
return {
|
|
100
|
+
'scan_info': {
|
|
101
|
+
'path': self.scan_path,
|
|
102
|
+
'timestamp': self.scan_timestamp,
|
|
103
|
+
'scanner_version': self.scanner_version,
|
|
104
|
+
'duration_seconds': self.scan_duration_seconds
|
|
105
|
+
},
|
|
106
|
+
'statistics': {
|
|
107
|
+
'total_files': self.total_files_scanned,
|
|
108
|
+
'total_lines': self.total_lines_scanned,
|
|
109
|
+
'total_findings': self.total_findings,
|
|
110
|
+
'by_severity': {
|
|
111
|
+
'critical': self.critical_count,
|
|
112
|
+
'high': self.high_count,
|
|
113
|
+
'medium': self.medium_count,
|
|
114
|
+
'low': self.low_count,
|
|
115
|
+
'info': self.info_count
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
'findings': [f.to_dict() for f in self.findings]
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class SecurityScanner:
|
|
123
|
+
"""
|
|
124
|
+
Main scanner class that orchestrates vulnerability detection.
|
|
125
|
+
|
|
126
|
+
This class coordinates the scanning process by:
|
|
127
|
+
1. Discovering Dart files in the target path
|
|
128
|
+
2. Loading and applying vulnerability patterns
|
|
129
|
+
3. Mapping findings to MASVS controls
|
|
130
|
+
4. Aggregating and returning results
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
VERSION = __version__
|
|
134
|
+
|
|
135
|
+
# Rules that look for problems in project configuration rather than in
|
|
136
|
+
# Dart code, mapped to the files they should read (relative to the
|
|
137
|
+
# project root). Only these rules are applied to these files.
|
|
138
|
+
CONFIG_FILE_RULES = {
|
|
139
|
+
# Outdated dependency versions are declared in pubspec.yaml
|
|
140
|
+
'V020': ['pubspec.yaml'],
|
|
141
|
+
# The minimum SDK version is set in the Android and iOS build files
|
|
142
|
+
'V021': [
|
|
143
|
+
'android/app/build.gradle',
|
|
144
|
+
'android/app/build.gradle.kts',
|
|
145
|
+
'ios/Podfile',
|
|
146
|
+
],
|
|
147
|
+
# Release builds are run from CI configuration and build scripts
|
|
148
|
+
'V024': [
|
|
149
|
+
'.github/workflows/*.yml',
|
|
150
|
+
'.github/workflows/*.yaml',
|
|
151
|
+
'.gitlab-ci.yml',
|
|
152
|
+
'codemagic.yaml',
|
|
153
|
+
'bitrise.yml',
|
|
154
|
+
'Makefile',
|
|
155
|
+
'*.sh',
|
|
156
|
+
'scripts/*.sh',
|
|
157
|
+
],
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
def __init__(self, config: ScannerConfig):
|
|
161
|
+
"""
|
|
162
|
+
Initialize the scanner with configuration.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
config: Scanner configuration object
|
|
166
|
+
"""
|
|
167
|
+
self.config = config
|
|
168
|
+
self.pattern_registry = PatternRegistry()
|
|
169
|
+
self.masvs_mapper = MasvsMapper()
|
|
170
|
+
|
|
171
|
+
def scan(self, path: Union[str, Path]) -> ScanResults:
|
|
172
|
+
"""
|
|
173
|
+
Scan a Flutter project or Dart file for vulnerabilities.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
path: Path to Flutter project directory or single Dart file
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
ScanResults object containing all findings
|
|
180
|
+
"""
|
|
181
|
+
start_time = datetime.now()
|
|
182
|
+
path = Path(path)
|
|
183
|
+
|
|
184
|
+
# Initialize results
|
|
185
|
+
results = ScanResults(
|
|
186
|
+
scan_path=str(path),
|
|
187
|
+
scan_timestamp=start_time.isoformat(),
|
|
188
|
+
scanner_version=self.VERSION,
|
|
189
|
+
total_files_scanned=0,
|
|
190
|
+
total_lines_scanned=0
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
# Discover Dart files
|
|
194
|
+
dart_files = self._discover_dart_files(path)
|
|
195
|
+
|
|
196
|
+
# Collect all Dart content for project-level analysis
|
|
197
|
+
all_dart_content = []
|
|
198
|
+
|
|
199
|
+
# Scan each file
|
|
200
|
+
for dart_file in dart_files:
|
|
201
|
+
file_findings, line_count, file_content = self._scan_file(dart_file)
|
|
202
|
+
results.findings.extend(file_findings)
|
|
203
|
+
results.total_files_scanned += 1
|
|
204
|
+
results.total_lines_scanned += line_count
|
|
205
|
+
all_dart_content.append(file_content)
|
|
206
|
+
|
|
207
|
+
# Scan project configuration files with the rules that target them
|
|
208
|
+
if path.is_dir():
|
|
209
|
+
for config_file, rule_ids in self._discover_config_files(path).items():
|
|
210
|
+
config_findings, line_count = self._scan_config_file(config_file, rule_ids)
|
|
211
|
+
results.findings.extend(config_findings)
|
|
212
|
+
results.total_files_scanned += 1
|
|
213
|
+
results.total_lines_scanned += line_count
|
|
214
|
+
|
|
215
|
+
# Check pubspec.yaml for project-level security packages
|
|
216
|
+
# Pass combined Dart content to check for sensitive functionality
|
|
217
|
+
combined_dart_content = '\n'.join(all_dart_content)
|
|
218
|
+
pubspec_findings = self._check_pubspec_security(path, combined_dart_content)
|
|
219
|
+
results.findings.extend(pubspec_findings)
|
|
220
|
+
|
|
221
|
+
# Apply severity filter
|
|
222
|
+
if self.config.min_severity:
|
|
223
|
+
results.findings = self._filter_by_severity(results.findings)
|
|
224
|
+
|
|
225
|
+
# Apply MASVS category filter
|
|
226
|
+
if self.config.masvs_categories:
|
|
227
|
+
results.findings = self._filter_by_category(results.findings)
|
|
228
|
+
|
|
229
|
+
# Calculate duration
|
|
230
|
+
end_time = datetime.now()
|
|
231
|
+
results.scan_duration_seconds = (end_time - start_time).total_seconds()
|
|
232
|
+
|
|
233
|
+
return results
|
|
234
|
+
|
|
235
|
+
def _discover_dart_files(self, path: Path) -> List[Path]:
|
|
236
|
+
"""
|
|
237
|
+
Discover all Dart files in the given path.
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
path: Directory or file path
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
List of Dart file paths
|
|
244
|
+
"""
|
|
245
|
+
if path.is_file():
|
|
246
|
+
if path.suffix == '.dart':
|
|
247
|
+
return [path]
|
|
248
|
+
return []
|
|
249
|
+
|
|
250
|
+
dart_files = []
|
|
251
|
+
|
|
252
|
+
# Directories to skip
|
|
253
|
+
skip_dirs = {'.dart_tool', 'build', '.git', '.idea', 'ios', 'android', 'web', 'linux', 'macos', 'windows', 'test', 'tests', 'test_driver', 'integration_test'}
|
|
254
|
+
|
|
255
|
+
for root, dirs, files in os.walk(path):
|
|
256
|
+
# Remove directories to skip
|
|
257
|
+
dirs[:] = [d for d in dirs if d not in skip_dirs]
|
|
258
|
+
|
|
259
|
+
for file in files:
|
|
260
|
+
if file.endswith('.dart'):
|
|
261
|
+
dart_files.append(Path(root) / file)
|
|
262
|
+
|
|
263
|
+
return dart_files
|
|
264
|
+
|
|
265
|
+
def _scan_file(self, file_path: Path) -> tuple[List[Finding], int, str]:
|
|
266
|
+
"""
|
|
267
|
+
Scan a single Dart file for vulnerabilities.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
file_path: Path to Dart file
|
|
271
|
+
|
|
272
|
+
Returns:
|
|
273
|
+
Tuple of (list of findings, line count, file content)
|
|
274
|
+
"""
|
|
275
|
+
findings = []
|
|
276
|
+
|
|
277
|
+
try:
|
|
278
|
+
with open(file_path, 'r', encoding='utf-8') as f:
|
|
279
|
+
content = f.read()
|
|
280
|
+
lines = content.split('\n')
|
|
281
|
+
line_count = len(lines)
|
|
282
|
+
except (IOError, UnicodeDecodeError) as e:
|
|
283
|
+
if self.config.verbose:
|
|
284
|
+
print(f"Warning: Could not read {file_path}: {e}")
|
|
285
|
+
return [], 0, ''
|
|
286
|
+
|
|
287
|
+
# Apply each pattern
|
|
288
|
+
for pattern in self.pattern_registry.get_all_patterns():
|
|
289
|
+
matches = pattern.search(content, lines)
|
|
290
|
+
|
|
291
|
+
for match in matches:
|
|
292
|
+
findings.append(self._make_finding(pattern, file_path, match))
|
|
293
|
+
|
|
294
|
+
return findings, line_count, content
|
|
295
|
+
|
|
296
|
+
def _discover_config_files(self, path: Path) -> Dict[Path, Set[str]]:
|
|
297
|
+
"""
|
|
298
|
+
Find the project configuration files read by CONFIG_FILE_RULES.
|
|
299
|
+
|
|
300
|
+
Args:
|
|
301
|
+
path: Project root directory
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
Mapping of each file found to the rule IDs that should read it
|
|
305
|
+
"""
|
|
306
|
+
config_files: Dict[Path, Set[str]] = {}
|
|
307
|
+
|
|
308
|
+
for rule_id, file_globs in self.CONFIG_FILE_RULES.items():
|
|
309
|
+
for file_glob in file_globs:
|
|
310
|
+
for file_path in sorted(path.glob(file_glob)):
|
|
311
|
+
if file_path.is_file():
|
|
312
|
+
config_files.setdefault(file_path, set()).add(rule_id)
|
|
313
|
+
|
|
314
|
+
return config_files
|
|
315
|
+
|
|
316
|
+
def _scan_config_file(self, file_path: Path, rule_ids: Set[str]) -> tuple[List[Finding], int]:
|
|
317
|
+
"""
|
|
318
|
+
Scan a configuration file with only the rules that target it.
|
|
319
|
+
|
|
320
|
+
Lines starting with '#' are comments in YAML, Podfiles and shell
|
|
321
|
+
scripts, so they are blanked before matching. Line numbers are kept
|
|
322
|
+
the same so findings still point at the right line. Gradle '//'
|
|
323
|
+
comments are already skipped by the pattern's false positive check.
|
|
324
|
+
|
|
325
|
+
Args:
|
|
326
|
+
file_path: Path to the configuration file
|
|
327
|
+
rule_ids: Vulnerability IDs to apply to this file
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
Tuple of (list of findings, line count)
|
|
331
|
+
"""
|
|
332
|
+
findings = []
|
|
333
|
+
|
|
334
|
+
try:
|
|
335
|
+
with open(file_path, 'r', encoding='utf-8') as f:
|
|
336
|
+
original_lines = f.read().split('\n')
|
|
337
|
+
except (IOError, UnicodeDecodeError) as e:
|
|
338
|
+
if self.config.verbose:
|
|
339
|
+
print(f"Warning: Could not read {file_path}: {e}")
|
|
340
|
+
return [], 0
|
|
341
|
+
|
|
342
|
+
lines = ['' if line.strip().startswith('#') else line for line in original_lines]
|
|
343
|
+
content = '\n'.join(lines)
|
|
344
|
+
|
|
345
|
+
for rule_id in sorted(rule_ids):
|
|
346
|
+
pattern = self.pattern_registry.get_pattern_by_id(rule_id)
|
|
347
|
+
if pattern is None:
|
|
348
|
+
continue
|
|
349
|
+
|
|
350
|
+
for match in pattern.search(content, lines):
|
|
351
|
+
findings.append(self._make_finding(pattern, file_path, match))
|
|
352
|
+
|
|
353
|
+
return findings, len(original_lines)
|
|
354
|
+
|
|
355
|
+
def _make_finding(self, pattern, file_path: Path, match: dict) -> Finding:
|
|
356
|
+
"""Build a Finding from a pattern match."""
|
|
357
|
+
return Finding(
|
|
358
|
+
vulnerability_id=pattern.vulnerability_id,
|
|
359
|
+
title=pattern.title,
|
|
360
|
+
description=pattern.description,
|
|
361
|
+
severity=pattern.severity,
|
|
362
|
+
file_path=str(file_path),
|
|
363
|
+
line_number=match['line_number'],
|
|
364
|
+
code_snippet=match['code_snippet'],
|
|
365
|
+
masvs_category=pattern.masvs_category,
|
|
366
|
+
masvs_control=pattern.masvs_control,
|
|
367
|
+
remediation=pattern.remediation,
|
|
368
|
+
cwe_id=pattern.cwe_id,
|
|
369
|
+
confidence=match.get('confidence', 'high')
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
def _filter_by_severity(self, findings: List[Finding]) -> List[Finding]:
|
|
373
|
+
"""Filter findings by minimum severity level."""
|
|
374
|
+
severity_order = ['info', 'low', 'medium', 'high', 'critical']
|
|
375
|
+
min_index = severity_order.index(self.config.min_severity)
|
|
376
|
+
|
|
377
|
+
return [f for f in findings if severity_order.index(f.severity) >= min_index]
|
|
378
|
+
|
|
379
|
+
def _filter_by_category(self, findings: List[Finding]) -> List[Finding]:
|
|
380
|
+
"""Filter findings by MASVS categories."""
|
|
381
|
+
return [f for f in findings if f.masvs_category in self.config.masvs_categories]
|
|
382
|
+
|
|
383
|
+
def _check_pubspec_security(self, path: Path, dart_files_content: str) -> List[Finding]:
|
|
384
|
+
"""
|
|
385
|
+
Check pubspec.yaml for security-related packages.
|
|
386
|
+
|
|
387
|
+
This checks for project-level security configurations like
|
|
388
|
+
root/jailbreak detection packages, but ONLY if the app
|
|
389
|
+
contains sensitive functionality.
|
|
390
|
+
|
|
391
|
+
Args:
|
|
392
|
+
path: Path to Flutter project directory
|
|
393
|
+
dart_files_content: Combined content of all scanned Dart files
|
|
394
|
+
|
|
395
|
+
Returns:
|
|
396
|
+
List of findings for missing security packages
|
|
397
|
+
"""
|
|
398
|
+
findings = []
|
|
399
|
+
|
|
400
|
+
# Find pubspec.yaml
|
|
401
|
+
if path.is_file():
|
|
402
|
+
pubspec_path = path.parent / 'pubspec.yaml'
|
|
403
|
+
else:
|
|
404
|
+
pubspec_path = path / 'pubspec.yaml'
|
|
405
|
+
|
|
406
|
+
# If no pubspec.yaml found, skip this check
|
|
407
|
+
if not pubspec_path.exists():
|
|
408
|
+
return findings
|
|
409
|
+
|
|
410
|
+
try:
|
|
411
|
+
with open(pubspec_path, 'r', encoding='utf-8') as f:
|
|
412
|
+
pubspec_content = f.read().lower()
|
|
413
|
+
except (IOError, UnicodeDecodeError):
|
|
414
|
+
return findings
|
|
415
|
+
|
|
416
|
+
# =====================================================
|
|
417
|
+
# V022: Check for root/jailbreak detection packages
|
|
418
|
+
# Only flag if app contains sensitive functionality
|
|
419
|
+
# =====================================================
|
|
420
|
+
|
|
421
|
+
# Step 1: Check if app has sensitive functionality
|
|
422
|
+
sensitive_indicators = [
|
|
423
|
+
# Crypto/Wallet related
|
|
424
|
+
r'encrypt\s*\(',
|
|
425
|
+
r'decrypt\s*\(',
|
|
426
|
+
r'wallet',
|
|
427
|
+
r'seed',
|
|
428
|
+
r'private[_]?key',
|
|
429
|
+
r'mnemonic',
|
|
430
|
+
r'crypto',
|
|
431
|
+
# Payment related
|
|
432
|
+
r'payment',
|
|
433
|
+
r'credit[_]?card',
|
|
434
|
+
r'stripe',
|
|
435
|
+
r'paypal',
|
|
436
|
+
r'checkout',
|
|
437
|
+
r'purchase',
|
|
438
|
+
# Banking related
|
|
439
|
+
r'bank',
|
|
440
|
+
r'transfer',
|
|
441
|
+
r'account[_]?balance',
|
|
442
|
+
r'transaction',
|
|
443
|
+
# Authentication related
|
|
444
|
+
r'biometric',
|
|
445
|
+
r'local[_]?auth',
|
|
446
|
+
r'flutter_secure_storage',
|
|
447
|
+
r'pin[_]?code',
|
|
448
|
+
# Health related
|
|
449
|
+
r'health[_]?data',
|
|
450
|
+
r'medical',
|
|
451
|
+
r'patient',
|
|
452
|
+
]
|
|
453
|
+
|
|
454
|
+
import re
|
|
455
|
+
dart_content_lower = dart_files_content.lower()
|
|
456
|
+
|
|
457
|
+
# Check if ANY sensitive indicator is found
|
|
458
|
+
has_sensitive_code = any(
|
|
459
|
+
re.search(indicator, dart_content_lower)
|
|
460
|
+
for indicator in sensitive_indicators
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
# If no sensitive code, don't flag V022
|
|
464
|
+
if not has_sensitive_code:
|
|
465
|
+
return findings
|
|
466
|
+
|
|
467
|
+
# Step 2: Check for root detection packages in pubspec.yaml
|
|
468
|
+
root_detection_packages = [
|
|
469
|
+
'flutter_jailbreak_detection',
|
|
470
|
+
'root_checker',
|
|
471
|
+
'safe_device',
|
|
472
|
+
'freerasp',
|
|
473
|
+
'jailbreak_detection',
|
|
474
|
+
'trust_fall',
|
|
475
|
+
]
|
|
476
|
+
|
|
477
|
+
has_root_detection = any(pkg in pubspec_content for pkg in root_detection_packages)
|
|
478
|
+
|
|
479
|
+
# Step 3: If sensitive code exists but no root detection, flag it
|
|
480
|
+
if not has_root_detection:
|
|
481
|
+
findings.append(Finding(
|
|
482
|
+
vulnerability_id='V022',
|
|
483
|
+
title='Missing Root/Jailbreak Detection',
|
|
484
|
+
description='App contains sensitive functionality (crypto, payments, secure storage, or biometrics) but does not include root/jailbreak detection. Rooted devices can bypass app security controls and access protected data.',
|
|
485
|
+
severity='medium',
|
|
486
|
+
file_path=str(pubspec_path),
|
|
487
|
+
line_number=1,
|
|
488
|
+
code_snippet='# Sensitive code detected but no root/jailbreak detection package found in dependencies',
|
|
489
|
+
masvs_category='RESILIENCE',
|
|
490
|
+
masvs_control='MASVS-RESILIENCE-1',
|
|
491
|
+
remediation='Add a root/jailbreak detection package to pubspec.yaml. Recommended packages: flutter_jailbreak_detection, freerasp, or safe_device.',
|
|
492
|
+
cwe_id='CWE-919',
|
|
493
|
+
confidence='high'
|
|
494
|
+
))
|
|
495
|
+
|
|
496
|
+
# =====================================================
|
|
497
|
+
# V013: Check for certificate pinning packages
|
|
498
|
+
# Only flag if app uses HTTP clients (Dio, http, HttpClient)
|
|
499
|
+
# but has no certificate pinning package installed
|
|
500
|
+
# =====================================================
|
|
501
|
+
|
|
502
|
+
# Step 1: Check if app uses HTTP client libraries
|
|
503
|
+
http_client_indicators = [
|
|
504
|
+
r'dio', # Dio package
|
|
505
|
+
r'package:http/', # http package
|
|
506
|
+
r'HttpClient', # dart:io HttpClient
|
|
507
|
+
]
|
|
508
|
+
|
|
509
|
+
uses_http_clients = any(
|
|
510
|
+
re.search(indicator, dart_files_content)
|
|
511
|
+
for indicator in http_client_indicators
|
|
512
|
+
)
|
|
513
|
+
|
|
514
|
+
# Step 2: Check pubspec.yaml for cert pinning packages
|
|
515
|
+
cert_pinning_packages = [
|
|
516
|
+
'http_certificate_pinning',
|
|
517
|
+
'ssl_pinning_plugin',
|
|
518
|
+
'dio_http2_adapter',
|
|
519
|
+
'certificate_pinning',
|
|
520
|
+
'trust_fall',
|
|
521
|
+
'freerasp', # freeRASP also includes cert pinning
|
|
522
|
+
]
|
|
523
|
+
|
|
524
|
+
has_cert_pinning = any(pkg in pubspec_content for pkg in cert_pinning_packages)
|
|
525
|
+
|
|
526
|
+
# Step 3: If app uses HTTP clients but no pinning, flag it
|
|
527
|
+
if uses_http_clients and not has_cert_pinning:
|
|
528
|
+
findings.append(Finding(
|
|
529
|
+
vulnerability_id='V013',
|
|
530
|
+
title='Missing Certificate Pinning',
|
|
531
|
+
description='App uses HTTP client libraries (Dio, http, or HttpClient) but does not include a certificate pinning package. Without pinning, attackers with CA-signed certificates can perform man-in-the-middle attacks.',
|
|
532
|
+
severity='medium',
|
|
533
|
+
file_path=str(pubspec_path),
|
|
534
|
+
line_number=1,
|
|
535
|
+
code_snippet='# HTTP client usage detected but no certificate pinning package found in dependencies',
|
|
536
|
+
masvs_category='NETWORK',
|
|
537
|
+
masvs_control='MASVS-NETWORK-2',
|
|
538
|
+
remediation='Add a certificate pinning package to pubspec.yaml. Recommended: http_certificate_pinning, ssl_pinning_plugin, or dio_http2_adapter. Pin to leaf certificate or public key hash.',
|
|
539
|
+
cwe_id='CWE-295',
|
|
540
|
+
confidence='high'
|
|
541
|
+
))
|
|
542
|
+
|
|
543
|
+
return findings
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Flutter Security Scanner - Main Entry Point
|
|
4
|
+
|
|
5
|
+
A static analysis tool for detecting security vulnerabilities in Flutter/Dart
|
|
6
|
+
applications with OWASP MASVS compliance mapping.
|
|
7
|
+
|
|
8
|
+
Author: Caleb Elebhose
|
|
9
|
+
Project: MSc Cybersecurity Final Year Project
|
|
10
|
+
University of Chester
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import sys
|
|
15
|
+
import json
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Optional
|
|
18
|
+
|
|
19
|
+
from flutter_security_analyzer import __version__
|
|
20
|
+
from flutter_security_analyzer.core.scanner import SecurityScanner
|
|
21
|
+
from flutter_security_analyzer.core.config import ScannerConfig
|
|
22
|
+
from flutter_security_analyzer.reporters.console_reporter import ConsoleReporter
|
|
23
|
+
from flutter_security_analyzer.reporters.json_reporter import JsonReporter
|
|
24
|
+
from flutter_security_analyzer.reporters.html_reporter import HtmlReporter
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def parse_arguments() -> argparse.Namespace:
|
|
28
|
+
"""Parse command line arguments."""
|
|
29
|
+
parser = argparse.ArgumentParser(
|
|
30
|
+
prog='flutter-security-analyzer',
|
|
31
|
+
description='Static security analysis tool for Flutter/Dart applications',
|
|
32
|
+
epilog='Part of MSc Cybersecurity Project - University of Chester'
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
parser.add_argument(
|
|
36
|
+
'path',
|
|
37
|
+
type=str,
|
|
38
|
+
help='Path to Flutter project or Dart file to scan'
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
'-o', '--output',
|
|
43
|
+
type=str,
|
|
44
|
+
default=None,
|
|
45
|
+
help='Output file path for report (default: stdout)'
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
parser.add_argument(
|
|
49
|
+
'-f', '--format',
|
|
50
|
+
type=str,
|
|
51
|
+
choices=['console', 'json', 'html'],
|
|
52
|
+
default='console',
|
|
53
|
+
help='Output format (default: console)'
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
'-s', '--severity',
|
|
58
|
+
type=str,
|
|
59
|
+
choices=['critical', 'high', 'medium', 'low', 'info'],
|
|
60
|
+
default='low',
|
|
61
|
+
help='Minimum severity level to report (default: low)'
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
parser.add_argument(
|
|
65
|
+
'-c', '--config',
|
|
66
|
+
type=str,
|
|
67
|
+
default=None,
|
|
68
|
+
help='Path to configuration file'
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
'--masvs-category',
|
|
73
|
+
type=str,
|
|
74
|
+
nargs='+',
|
|
75
|
+
choices=['STORAGE', 'CRYPTO', 'AUTH', 'NETWORK', 'PLATFORM', 'CODE', 'RESILIENCE', 'PRIVACY'],
|
|
76
|
+
default=None,
|
|
77
|
+
help='Filter by MASVS categories'
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
parser.add_argument(
|
|
81
|
+
'-v', '--verbose',
|
|
82
|
+
action='store_true',
|
|
83
|
+
help='Enable verbose output'
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
parser.add_argument(
|
|
87
|
+
'--version',
|
|
88
|
+
action='version',
|
|
89
|
+
version=f'%(prog)s {__version__}'
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
return parser.parse_args()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def create_reporter(format_type: str, output_path: Optional[str]):
|
|
96
|
+
"""Factory function to create appropriate reporter."""
|
|
97
|
+
reporters = {
|
|
98
|
+
'console': ConsoleReporter,
|
|
99
|
+
'json': JsonReporter,
|
|
100
|
+
'html': HtmlReporter
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
reporter_class = reporters.get(format_type, ConsoleReporter)
|
|
104
|
+
return reporter_class(output_path)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def main() -> int:
|
|
108
|
+
"""Main entry point for the scanner."""
|
|
109
|
+
args = parse_arguments()
|
|
110
|
+
|
|
111
|
+
# Validate input path
|
|
112
|
+
scan_path = Path(args.path)
|
|
113
|
+
if not scan_path.exists():
|
|
114
|
+
print(f"Error: Path '{args.path}' does not exist.", file=sys.stderr)
|
|
115
|
+
return 1
|
|
116
|
+
|
|
117
|
+
# Load configuration
|
|
118
|
+
config = ScannerConfig(
|
|
119
|
+
min_severity=args.severity,
|
|
120
|
+
masvs_categories=args.masvs_category,
|
|
121
|
+
verbose=args.verbose,
|
|
122
|
+
config_file=args.config
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# Initialize scanner
|
|
126
|
+
scanner = SecurityScanner(config)
|
|
127
|
+
|
|
128
|
+
# Perform scan
|
|
129
|
+
if args.verbose:
|
|
130
|
+
print(f"Scanning: {scan_path}")
|
|
131
|
+
|
|
132
|
+
results = scanner.scan(scan_path)
|
|
133
|
+
|
|
134
|
+
# Generate report
|
|
135
|
+
reporter = create_reporter(args.format, args.output)
|
|
136
|
+
reporter.generate(results)
|
|
137
|
+
|
|
138
|
+
# Return exit code based on findings
|
|
139
|
+
critical_count = sum(1 for r in results.findings if r.severity == 'critical')
|
|
140
|
+
high_count = sum(1 for r in results.findings if r.severity == 'high')
|
|
141
|
+
|
|
142
|
+
if critical_count > 0:
|
|
143
|
+
return 2 # Critical findings
|
|
144
|
+
elif high_count > 0:
|
|
145
|
+
return 1 # High severity findings
|
|
146
|
+
return 0 # Success
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
if __name__ == '__main__':
|
|
150
|
+
sys.exit(main())
|