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,514 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Base Pattern Module
|
|
3
|
+
|
|
4
|
+
Defines the base class for all vulnerability detection patterns.
|
|
5
|
+
Includes a shared Dart/Flutter language whitelist that filters common
|
|
6
|
+
false positive patterns before individual vulnerability patterns run.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
import math
|
|
11
|
+
from abc import ABC, abstractmethod
|
|
12
|
+
from collections import Counter
|
|
13
|
+
from typing import List, Dict, Any, Optional
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class PatternMatch:
|
|
19
|
+
"""Represents a pattern match in source code."""
|
|
20
|
+
line_number: int
|
|
21
|
+
code_snippet: str
|
|
22
|
+
matched_text: str
|
|
23
|
+
confidence: str = 'high' # high, medium, low
|
|
24
|
+
context: Optional[Dict[str, Any]] = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ============================================================================
|
|
28
|
+
# DART/FLUTTER LANGUAGE WHITELIST
|
|
29
|
+
#
|
|
30
|
+
# Common Dart and Flutter coding patterns that contain security-related
|
|
31
|
+
# keywords (password, token, key, session, secret, auth, pin) but are
|
|
32
|
+
# NOT security vulnerabilities. These are checked before any individual
|
|
33
|
+
# vulnerability pattern runs, eliminating false positives at the source.
|
|
34
|
+
#
|
|
35
|
+
# Three categories:
|
|
36
|
+
# 1. NAMING CONVENTIONS: Developer naming patterns where security keywords
|
|
37
|
+
# appear in identifiers, not in actual data
|
|
38
|
+
# 2. LANGUAGE FEATURES: Dart/Flutter syntax that uses security keywords
|
|
39
|
+
# as part of the language itself
|
|
40
|
+
# 3. CONFIGURATION PATTERNS: Config keys and settings that contain
|
|
41
|
+
# security keywords as descriptive labels, not actual secrets
|
|
42
|
+
# ============================================================================
|
|
43
|
+
|
|
44
|
+
DART_LANGUAGE_WHITELIST = [
|
|
45
|
+
|
|
46
|
+
# ===================================================================
|
|
47
|
+
# CATEGORY 1: NAMING CONVENTIONS
|
|
48
|
+
# Developers name things after what they do. A function that handles
|
|
49
|
+
# password reset is called resetPassword(). A model for auth sessions
|
|
50
|
+
# is called AuthSession. The security keyword is in the IDENTIFIER,
|
|
51
|
+
# not in the DATA.
|
|
52
|
+
# ===================================================================
|
|
53
|
+
|
|
54
|
+
# 1.1 Flutter constant naming conventions
|
|
55
|
+
# kOption*, kKey*, kWindow*, kEvent*, kDefault*, kMin*, kMax* prefixes
|
|
56
|
+
# e.g., kOptionAllowDeepLinkPassword, kWindowEventActiveSession
|
|
57
|
+
# e.g., kDefaultSessionTimeout, kMinPasswordLength
|
|
58
|
+
r'(?:const\s+(?:\w+\s+)*)?_?k(?:Option|Key|Window|Event|Default|Min|Max|Is|Has|Enable|Disable|Allow)\w*\s*=',
|
|
59
|
+
|
|
60
|
+
# 1.2 Function/method DECLARATIONS with security keywords in the name
|
|
61
|
+
# Covers all Dart return types including void, Future, Stream, FutureOr
|
|
62
|
+
# e.g., void wrongPasswordDialog(...), Future<bool> validateToken(...)
|
|
63
|
+
# e.g., Stream<AuthState> watchSession(), bool isTokenExpired()
|
|
64
|
+
r'(?:void|Future|FutureOr|Stream|Widget|Function|static|bool|String|int|double|dynamic|List|Map|Set|Iterator|Iterable|num)\s*<?[\w,\s]*>?\s+\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential|[Cc]ertificate)\w*\s*[<(]',
|
|
65
|
+
|
|
66
|
+
# 1.3 Function/method CALLS where the name contains the keyword
|
|
67
|
+
# e.g., showPasswordDialog(), validateToken(), checkSessionStatus()
|
|
68
|
+
# e.g., parseAuthResponse(), encodeCredentials(), disposeSession()
|
|
69
|
+
r'(?:wrong|show|on|handle|validate|check|verify|reset|forgot|change|update|set|get|create|build|clear|close|open|init|dispose|notify|parse|format|encode|decode|fetch|load|save|store|delete|remove|revoke|refresh|invalidate|emit|yield|return|throw|assert|expect|mock|stub|fake|when|verify|find|lookup|resolve|provide|inject|register|unregister|observe|watch|listen|subscribe|cancel|start|stop|toggle|enable|disable|grant|deny|request|approve|reject|confirm|accept|decline|prompt|ask|require|ensure|sanitize|hash|compare|match|test|is|has|can|should|will|must|need|try|attempt|process|convert|transform|map|filter|reduce|sort|group|merge|split|join|wrap|unwrap|extract|insert|append|prepend|push|pop|peek|enqueue|dequeue)\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential|[Cc]ertificate)\w*\s*[<(]',
|
|
70
|
+
|
|
71
|
+
# 1.4 Class and type declarations/references
|
|
72
|
+
# e.g., class PasswordValidator, class AuthSession, class TokenManager
|
|
73
|
+
# e.g., mixin SessionMixin, extension AuthExtension on User
|
|
74
|
+
r'(?:class|mixin|extension|enum|typedef)\s+\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential|[Cc]ertificate)\w*',
|
|
75
|
+
|
|
76
|
+
# 1.5 Type annotations and generic type parameters
|
|
77
|
+
# e.g., PasswordController controller, AuthState state, TokenResponse response
|
|
78
|
+
# e.g., List<SessionModel> sessions, Map<String, AuthToken> tokens
|
|
79
|
+
# e.g., Future<PasswordResetResult> result
|
|
80
|
+
r'(?:[A-Z]\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential|[Cc]ertificate)\w*)\s+\w+\s*[;=,)\]]',
|
|
81
|
+
r'(?:List|Map|Set|Future|Stream|Iterable|FutureOr|ValueNotifier|StateNotifier|ChangeNotifier|Provider|Riverpod)<\s*\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential)\w*\s*>',
|
|
82
|
+
|
|
83
|
+
# 1.6 Enum values and enum member access
|
|
84
|
+
# e.g., AuthState.authenticated, TokenType.bearer, SessionStatus.active
|
|
85
|
+
# e.g., PasswordStrength.strong, KeyAlgorithm.rsa256
|
|
86
|
+
r'\w+(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential)\w*\.\w+(?:\s*[;,)\]:]|\s*$)',
|
|
87
|
+
|
|
88
|
+
# 1.7 Code-generated model fields (freezed, mappable, json_serializable, built_value)
|
|
89
|
+
# e.g., _$saveToGallery(ReceiveSessionState v), Field<ReceiveSessionState>
|
|
90
|
+
# e.g., _$AuthResponseFromJson, _$TokenModelCopyWith
|
|
91
|
+
r'_\$\w*(?:[Ss]ession|[Tt]oken|[Kk]ey|[Pp]assword|[Aa]uth|[Cc]redential|[Ss]ecret)',
|
|
92
|
+
r'Field<\w*(?:[Ss]ession|[Tt]oken|[Kk]ey|[Pp]assword|[Aa]uth|[Cc]redential|[Ss]ecret)',
|
|
93
|
+
|
|
94
|
+
# 1.8 Named constructors and factory methods
|
|
95
|
+
# e.g., Token.fromJson(), Session.create(), AuthState.initial()
|
|
96
|
+
# e.g., Password.empty(), Credential.fromMap()
|
|
97
|
+
r'\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential)\w*\.(?:from[A-Z]\w*|create|initial|empty|none|unknown|defaults?|copy[Ww]ith|to[A-Z]\w*|parse|try[A-Z]\w*)\s*\(',
|
|
98
|
+
|
|
99
|
+
# 1.9 Getter and setter declarations
|
|
100
|
+
# e.g., String get sessionId => _id, set authToken(String value)
|
|
101
|
+
# e.g., bool get isAuthenticated, bool get hasValidToken
|
|
102
|
+
r'(?:get|set)\s+\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential)\w*',
|
|
103
|
+
r'(?:get|set)\s+(?:is|has|can|should|needs?)\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential)\w*',
|
|
104
|
+
|
|
105
|
+
# 1.10 Variable declarations that are clearly type/state/status variables
|
|
106
|
+
# e.g., bool isPasswordVisible, bool hasToken, AuthStatus authStatus
|
|
107
|
+
# e.g., int tokenRetryCount, String passwordHint
|
|
108
|
+
r'(?:bool|int|double|num)\s+(?:is|has|can|should|needs?|was|will|did)\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential)\w*',
|
|
109
|
+
|
|
110
|
+
# ===================================================================
|
|
111
|
+
# CATEGORY 2: DART/FLUTTER LANGUAGE FEATURES
|
|
112
|
+
# Dart syntax and Flutter framework APIs that use security keywords
|
|
113
|
+
# as part of the language/framework itself, not as application data.
|
|
114
|
+
# ===================================================================
|
|
115
|
+
|
|
116
|
+
# 2.1 Flutter widget constructor super.key parameter
|
|
117
|
+
# Every StatelessWidget and StatefulWidget has an optional Key parameter
|
|
118
|
+
# e.g., const MyWidget({required this.title, super.key})
|
|
119
|
+
r'super\.key',
|
|
120
|
+
|
|
121
|
+
# 2.2 Map/Iterable .keys property access
|
|
122
|
+
# Dart Map has a .keys getter that returns all keys
|
|
123
|
+
# e.g., onTapMap.keys.toList(), preferences.keys.where(...)
|
|
124
|
+
r'\w+\.keys\b(?!\s*[:=])',
|
|
125
|
+
|
|
126
|
+
# 2.3 Dart null safety and emptiness checks on security-named variables
|
|
127
|
+
# These are type safety checks, not security validation
|
|
128
|
+
# e.g., password.isNotEmpty, pin?.isEmpty, token == null
|
|
129
|
+
r'(?:password|pin|token|secret|key|credential|session)(?:\?)?\.(?:isNotEmpty|isEmpty)\b',
|
|
130
|
+
r'if\s*\(\s*(?:pin|password|token|secret|credential|session)\s*[!=]=\s*null\s*\)',
|
|
131
|
+
|
|
132
|
+
# 2.4 Constructor field declarations (this.fieldName parameters)
|
|
133
|
+
# e.g., required this.androidId, required this.sessionKey
|
|
134
|
+
# e.g., this.passwordController, this.tokenExpiry
|
|
135
|
+
r'(?:required\s+)?this\.(?:androidId|sessionId|tokenId|keyId|authId|passwordController|tokenExpiry|sessionTimeout|authState|keyStore|pinController|credentialManager)',
|
|
136
|
+
|
|
137
|
+
# 2.5 Dart annotations and metadata
|
|
138
|
+
# e.g., @JsonKey(name: 'auth_token'), @HiveField(3, defaultValue: '')
|
|
139
|
+
# e.g., @override, @protected on security-related methods
|
|
140
|
+
r"""@(?:JsonKey|HiveField|HiveType|FreezedUnionValue|Default|JsonSerializable|MappableField|BuiltValue|column|Column|Entity)\s*\([^)]*(?:password|token|secret|auth|session|key|pin|credential)""",
|
|
141
|
+
|
|
142
|
+
# 2.6 Dart typedef and function type aliases
|
|
143
|
+
# e.g., typedef TokenCallback = void Function(String token)
|
|
144
|
+
# e.g., typedef PasswordValidator = bool Function(String)
|
|
145
|
+
r'typedef\s+\w*(?:[Pp]assword|[Tt]oken|[Ss]ecret|[Aa]uth|[Ss]ession|[Kk]ey|[Pp]in|[Cc]redential)\w*\s*=',
|
|
146
|
+
|
|
147
|
+
# 2.7 Dart cascade operator on security-named objects
|
|
148
|
+
# e.g., passwordController..clear()..dispose()
|
|
149
|
+
r'\w*(?:[Pp]assword|[Tt]oken|[Ss]ession|[Aa]uth|[Kk]ey|[Pp]in)\w*\s*\.\.',
|
|
150
|
+
|
|
151
|
+
# 2.8 Import and export statements referencing security-named files/packages
|
|
152
|
+
# e.g., import 'package:auth/auth.dart', import 'services/session_service.dart'
|
|
153
|
+
r"""(?:import|export|part)\s+['"].*(?:password|token|secret|auth|session|key|pin|credential)""",
|
|
154
|
+
|
|
155
|
+
# 2.9 String interpolation in UI/display strings (not logging)
|
|
156
|
+
# When the line contains Text(), title:, label:, hint:, message:, description:
|
|
157
|
+
# the interpolated security keyword is for display, not data leakage
|
|
158
|
+
r'(?:Text|title|label|hint|message|description|tooltip|placeholder|helperText|errorText|counterText|prefixText|suffixText|semanticLabel)\s*[:(]\s*["\'].*(?:password|token|session|auth|key|pin)',
|
|
159
|
+
|
|
160
|
+
# 2.10 Test framework assertions and matchers
|
|
161
|
+
# e.g., expect(password, isNotNull), verify(mockAuth.login(any))
|
|
162
|
+
# e.g., when(mockSession.getToken()).thenReturn('test')
|
|
163
|
+
r'(?:expect|verify|when|setUp|tearDown|group|test|testWidgets)\s*\(.*(?:password|token|secret|auth|session|key|pin|credential)',
|
|
164
|
+
|
|
165
|
+
# ===================================================================
|
|
166
|
+
# CATEGORY 3: CONFIGURATION PATTERNS
|
|
167
|
+
# Config keys, settings, and constants that contain security keywords
|
|
168
|
+
# as descriptive labels, not as actual secrets or sensitive data.
|
|
169
|
+
# ===================================================================
|
|
170
|
+
|
|
171
|
+
# 3.1 Config option constants with kebab-case values (pure lowercase + hyphens)
|
|
172
|
+
# e.g., const key = 'disable-change-permanent-password'
|
|
173
|
+
# Excludes values with digits (which could be API keys like sk-proj-abc123)
|
|
174
|
+
r"""(?:const|final)\s+(?:\w+\s+)*\w+\s*=\s*['"][a-z][a-z\-]{2,60}['"]""",
|
|
175
|
+
|
|
176
|
+
# 3.2 Config option constants with snake_case values (lowercase + underscores)
|
|
177
|
+
# e.g., static const refreshToken = 'refresh_token', const _key = 'auth_state'
|
|
178
|
+
r"""static\s+const\s+(?:\w+\s+)*\w+\s*=\s*['"][a-z_]{3,30}['"]""",
|
|
179
|
+
|
|
180
|
+
# 3.3 Variables ending in Key with config-style values
|
|
181
|
+
# EXCLUDES actual secret-holding variable names
|
|
182
|
+
r"""(?:const|final)\s+(?:\w+\s+)*(?!api[Kk]ey|secret[Kk]ey|private[Kk]ey|auth[Kk]ey|aes[Kk]ey|encryption[Kk]ey|hmac[Kk]ey|signing[Kk]ey|master[Kk]ey|server[Kk]ey|client[Kk]ey)\w*[Kk]ey\w*\s*=\s*['"][^'"]{3,60}['"]""",
|
|
183
|
+
|
|
184
|
+
# 3.4 Private constants with app-specific prefixes (preferences/storage keys)
|
|
185
|
+
# e.g., const _showToken = 'ls_show_token', const _authKey = 'app_auth_key'
|
|
186
|
+
r"""const\s+_\w+\s*=\s*['"](?:ls_|app_|pref_|sp_|hive_|box_|cache_|db_|store_)[^'"]+['"]""",
|
|
187
|
+
|
|
188
|
+
# 3.5 Named parameters for store/platform product IDs
|
|
189
|
+
# e.g., androidId: 'com.app.donate_5', productId: 'premium_token'
|
|
190
|
+
r"""androidId\s*:\s*['"]""",
|
|
191
|
+
|
|
192
|
+
# 3.6 Environment variable lookups (reading config, not hardcoding)
|
|
193
|
+
# e.g., Platform.environment['API_KEY'], dotenv.get('SECRET')
|
|
194
|
+
# e.g., const.fromEnvironment('AUTH_TOKEN')
|
|
195
|
+
r"""(?:Platform\.environment|dotenv\.(?:get|env)|String\.fromEnvironment|bool\.fromEnvironment|int\.fromEnvironment|const\.fromEnvironment)\s*[\[(]\s*['"]""",
|
|
196
|
+
|
|
197
|
+
# 3.7 JSON/Map key access for parsing (reading field names, not secrets)
|
|
198
|
+
# e.g., json['password'], data['auth_token'], map['session_id']
|
|
199
|
+
# Only when preceded by a variable name (not print/log)
|
|
200
|
+
r"""\w+\s*\[\s*['"](?:password|token|secret|auth|session|key|pin|credential)[^'"]*['"]\s*\]""",
|
|
201
|
+
|
|
202
|
+
# 3.8 Route/path definitions containing security keywords
|
|
203
|
+
# e.g., '/auth/login', '/api/v1/token/refresh', '/reset-password'
|
|
204
|
+
r"""(?:route|path|url|uri|endpoint|api)\s*[:=]\s*['"][^'"]*(?:password|token|auth|session|login|logout|register|verify|reset|forgot)[^'"]*['"]""",
|
|
205
|
+
|
|
206
|
+
# 3.9 SharedPreferences/Hive box key name constants
|
|
207
|
+
# When the constant is defining the KEY NAME, not storing actual data
|
|
208
|
+
# e.g., static const tokenKey = 'user_auth_token' (key name)
|
|
209
|
+
# vs prefs.setString('user_auth_token', actualToken) (storing data - NOT whitelisted)
|
|
210
|
+
r"""(?:static\s+)?const\s+\w*(?:[Kk]ey|[Nn]ame|[Ff]ield|[Cc]olumn|[Pp]roperty)\s*=\s*['"][^'"]*(?:password|token|auth|session|secret|pin|credential)[^'"]*['"]""",
|
|
211
|
+
|
|
212
|
+
# 3.10 Error/exception message strings containing security keywords
|
|
213
|
+
# e.g., throw Exception('Invalid session'), FormatException('Bad token format')
|
|
214
|
+
# e.g., ArgumentError('Password cannot be null')
|
|
215
|
+
r"""(?:throw\s+\w*(?:Exception|Error|Failure)|(?:Exception|Error|Failure|FormatException|ArgumentError|StateError|AssertionError)\s*\()\s*['"][^'"]*(?:password|token|auth|session|secret|key|pin|credential)""",
|
|
216
|
+
]
|
|
217
|
+
|
|
218
|
+
# Compile the whitelist once for performance
|
|
219
|
+
_COMPILED_WHITELIST = [
|
|
220
|
+
re.compile(p, re.MULTILINE | re.IGNORECASE)
|
|
221
|
+
for p in DART_LANGUAGE_WHITELIST
|
|
222
|
+
]
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# ============================================================================
|
|
226
|
+
# SECRET VALUE HEURISTICS (V001 - Hardcoded API Keys/Secrets)
|
|
227
|
+
#
|
|
228
|
+
# V001's name-based patterns fire whenever an identifier contains "key",
|
|
229
|
+
# "secret", "password", "token" etc. That produces false positives on things
|
|
230
|
+
# like `carbonPassword = 'assets/icons/carbon_password.svg'` (an asset path)
|
|
231
|
+
# or `forgotPassword = '/forgot_password'` (a route). These helpers add a
|
|
232
|
+
# check that the matched STRING VALUE actually looks like a credential, not
|
|
233
|
+
# just that the variable name contains a security keyword.
|
|
234
|
+
# ============================================================================
|
|
235
|
+
|
|
236
|
+
# Well-known credential formats - if the value matches one of these it is a
|
|
237
|
+
# secret regardless of length/entropy (e.g. Firebase's AIza... web API keys).
|
|
238
|
+
_KNOWN_SECRET_FORMATS = [
|
|
239
|
+
re.compile(r'^(?:sk|pk|rk)-[A-Za-z0-9_-]{10,}$'), # OpenAI/Stripe-style
|
|
240
|
+
re.compile(r'^AIza[0-9A-Za-z_-]{10,}$'), # Google / Firebase
|
|
241
|
+
re.compile(r'^(?:gh[posu]|github_pat)_[A-Za-z0-9_]{20,}$'), # GitHub tokens
|
|
242
|
+
re.compile(r'^xox[baprs]-[A-Za-z0-9-]{10,}$'), # Slack tokens
|
|
243
|
+
re.compile(r'^AKIA[0-9A-Z]{16}$'), # AWS access key id
|
|
244
|
+
re.compile(r'^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$'), # JWT
|
|
245
|
+
re.compile(r'^[0-9a-fA-F]{32,}$'), # long hex secret
|
|
246
|
+
]
|
|
247
|
+
|
|
248
|
+
_ASSET_EXTENSION_RE = re.compile(
|
|
249
|
+
r'\.(?:svg|png|jpe?g|gif|webp|json|ya?ml|dart|txt|pdf|mp[34]|ttf|otf|riv|lottie|html?|css|xml)$',
|
|
250
|
+
re.IGNORECASE,
|
|
251
|
+
)
|
|
252
|
+
_ASSET_PATH_PREFIXES = ('assets/', 'lib/', 'packages/', 'fonts/', 'images/', 'icons/')
|
|
253
|
+
# Multi-segment snake_case / kebab-case: route names, preference keys, config
|
|
254
|
+
# option ids ('forgot_password', 'refresh_token', 'allow-deep-link-password').
|
|
255
|
+
# A separator is required so single opaque words ('secret', 'hunter2') are NOT
|
|
256
|
+
# treated as identifiers and still get flagged.
|
|
257
|
+
_MULTI_SEGMENT_ID_RE = re.compile(r'^[a-z0-9]+(?:[_-][a-z0-9]+)+$')
|
|
258
|
+
_PLAIN_URL_RE = re.compile(r'^https?://[^\s@]+$', re.IGNORECASE)
|
|
259
|
+
|
|
260
|
+
_STRING_LITERAL_RE = re.compile(r'"([^"]*)"|\'([^\']*)\'')
|
|
261
|
+
|
|
262
|
+
# A long value with almost no variety (e.g. 'xxxxxxxxxxxxxxxx') is a redaction
|
|
263
|
+
# or placeholder, not a real secret.
|
|
264
|
+
_PLACEHOLDER_MIN_LENGTH = 12
|
|
265
|
+
_PLACEHOLDER_MAX_ENTROPY = 2.0
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _shannon_entropy(value: str) -> float:
|
|
269
|
+
"""Return the Shannon entropy of a string in bits per character."""
|
|
270
|
+
if not value:
|
|
271
|
+
return 0.0
|
|
272
|
+
counts = Counter(value)
|
|
273
|
+
length = len(value)
|
|
274
|
+
return -sum(
|
|
275
|
+
(count / length) * math.log2(count / length)
|
|
276
|
+
for count in counts.values()
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _extract_string_literals(text: str) -> List[str]:
|
|
281
|
+
"""Extract the contents of every single- or double-quoted literal in text."""
|
|
282
|
+
return [a or b for a, b in _STRING_LITERAL_RE.findall(text)]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def looks_like_secret(value: str) -> bool:
|
|
286
|
+
"""Heuristic: does this string VALUE look like an actual credential?
|
|
287
|
+
|
|
288
|
+
Used to filter V001 false positives where a security keyword appears in
|
|
289
|
+
the variable name but the assigned value is an asset path, route, URL,
|
|
290
|
+
or other non-secret.
|
|
291
|
+
"""
|
|
292
|
+
v = value.strip()
|
|
293
|
+
|
|
294
|
+
# 1. Known credential formats are always secrets (covers Firebase AIza keys).
|
|
295
|
+
for fmt in _KNOWN_SECRET_FORMATS:
|
|
296
|
+
if fmt.match(v):
|
|
297
|
+
return True
|
|
298
|
+
|
|
299
|
+
# 2. Structural non-secrets - the shapes the reviewer flagged as false
|
|
300
|
+
# positives (asset paths, routes, config-option ids, display strings).
|
|
301
|
+
if not v:
|
|
302
|
+
return False
|
|
303
|
+
if any(ch.isspace() for ch in v): # human-readable text
|
|
304
|
+
return False
|
|
305
|
+
if v.startswith(('/', './', '../')): # route / relative path
|
|
306
|
+
return False
|
|
307
|
+
if v.lower().startswith(_ASSET_PATH_PREFIXES):
|
|
308
|
+
return False
|
|
309
|
+
if _ASSET_EXTENSION_RE.search(v): # asset filename
|
|
310
|
+
return False
|
|
311
|
+
if _PLAIN_URL_RE.match(v): # URL with no embedded credentials
|
|
312
|
+
return False
|
|
313
|
+
if _MULTI_SEGMENT_ID_RE.match(v): # snake_case / kebab-case identifier
|
|
314
|
+
return False
|
|
315
|
+
|
|
316
|
+
# 3. Long, near-zero-variety strings are placeholders / redactions.
|
|
317
|
+
if len(v) >= _PLACEHOLDER_MIN_LENGTH and _shannon_entropy(v) < _PLACEHOLDER_MAX_ENTROPY:
|
|
318
|
+
return False
|
|
319
|
+
|
|
320
|
+
# 4. Anything else assigned to a secret-named identifier is treated as a
|
|
321
|
+
# real credential. Missing a hardcoded secret is worse than an occasional
|
|
322
|
+
# false positive on an opaque value.
|
|
323
|
+
return True
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
class BasePattern(ABC):
|
|
327
|
+
"""
|
|
328
|
+
Abstract base class for vulnerability detection patterns.
|
|
329
|
+
|
|
330
|
+
All vulnerability patterns must inherit from this class and implement
|
|
331
|
+
the search method.
|
|
332
|
+
"""
|
|
333
|
+
|
|
334
|
+
vulnerability_id: str
|
|
335
|
+
title: str
|
|
336
|
+
description: str
|
|
337
|
+
severity: str
|
|
338
|
+
masvs_category: str
|
|
339
|
+
masvs_control: str
|
|
340
|
+
remediation: str
|
|
341
|
+
cwe_id: str
|
|
342
|
+
patterns: List[str]
|
|
343
|
+
|
|
344
|
+
def __init__(self):
|
|
345
|
+
"""Initialize the pattern and compile regex patterns."""
|
|
346
|
+
self._compiled_patterns = [
|
|
347
|
+
re.compile(p, re.MULTILINE | re.IGNORECASE)
|
|
348
|
+
for p in self.patterns
|
|
349
|
+
]
|
|
350
|
+
|
|
351
|
+
def search(self, content: str, lines: List[str]) -> List[Dict[str, Any]]:
|
|
352
|
+
"""
|
|
353
|
+
Search for pattern matches in the given content.
|
|
354
|
+
|
|
355
|
+
Args:
|
|
356
|
+
content: Full file content as string
|
|
357
|
+
lines: File content split into lines
|
|
358
|
+
|
|
359
|
+
Returns:
|
|
360
|
+
List of match dictionaries (deduplicated by line number)
|
|
361
|
+
"""
|
|
362
|
+
matches = []
|
|
363
|
+
seen_lines = set() # Track which lines we've already matched
|
|
364
|
+
|
|
365
|
+
for pattern in self._compiled_patterns:
|
|
366
|
+
for match in pattern.finditer(content):
|
|
367
|
+
line_number = content[:match.start()].count('\n') + 1
|
|
368
|
+
|
|
369
|
+
# Skip if we already have a finding on this line for this vulnerability
|
|
370
|
+
if line_number in seen_lines:
|
|
371
|
+
continue
|
|
372
|
+
|
|
373
|
+
if self._is_false_positive(match, content, lines, line_number):
|
|
374
|
+
continue
|
|
375
|
+
|
|
376
|
+
code_snippet = self._get_code_snippet(lines, line_number)
|
|
377
|
+
|
|
378
|
+
matches.append({
|
|
379
|
+
'line_number': line_number,
|
|
380
|
+
'code_snippet': code_snippet,
|
|
381
|
+
'matched_text': match.group(),
|
|
382
|
+
'confidence': self._calculate_confidence(match, content, lines)
|
|
383
|
+
})
|
|
384
|
+
|
|
385
|
+
seen_lines.add(line_number) # Mark this line as matched
|
|
386
|
+
|
|
387
|
+
return matches
|
|
388
|
+
|
|
389
|
+
def _get_code_snippet(self, lines: List[str], line_number: int, context: int = 2) -> str:
|
|
390
|
+
"""Extract code snippet with surrounding context."""
|
|
391
|
+
start = max(0, line_number - 1 - context)
|
|
392
|
+
end = min(len(lines), line_number + context)
|
|
393
|
+
|
|
394
|
+
snippet_lines = []
|
|
395
|
+
for i in range(start, end):
|
|
396
|
+
prefix = '>>> ' if i == line_number - 1 else ' '
|
|
397
|
+
snippet_lines.append(f"{i + 1:4d} {prefix}{lines[i]}")
|
|
398
|
+
|
|
399
|
+
return '\n'.join(snippet_lines)
|
|
400
|
+
|
|
401
|
+
def _is_false_positive(self, match: re.Match, content: str, lines: List[str], line_number: int) -> bool:
|
|
402
|
+
"""Check if match is a false positive.
|
|
403
|
+
|
|
404
|
+
Three-level false positive checking:
|
|
405
|
+
1. SHARED WHITELIST: Dart/Flutter language patterns that are never vulnerabilities
|
|
406
|
+
2. Comment detection: Lines starting with // or /* or *
|
|
407
|
+
3. Pattern-specific filters (handled by RegexPattern subclass)
|
|
408
|
+
"""
|
|
409
|
+
line = lines[line_number - 1]
|
|
410
|
+
|
|
411
|
+
# Level 1: Check against the shared Dart/Flutter language whitelist
|
|
412
|
+
# This catches common false positives from naming conventions,
|
|
413
|
+
# language features, and configuration patterns
|
|
414
|
+
for wp in _COMPILED_WHITELIST:
|
|
415
|
+
if wp.search(line):
|
|
416
|
+
return True
|
|
417
|
+
|
|
418
|
+
# Level 2: Comment detection
|
|
419
|
+
stripped = line.strip()
|
|
420
|
+
if stripped.startswith('//') or stripped.startswith('/*') or stripped.startswith('*'):
|
|
421
|
+
return True
|
|
422
|
+
|
|
423
|
+
return False
|
|
424
|
+
|
|
425
|
+
def _calculate_confidence(self, match: re.Match, content: str, lines: List[str]) -> str:
|
|
426
|
+
"""Calculate confidence level for the match."""
|
|
427
|
+
return 'high'
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
class RegexPattern(BasePattern):
|
|
431
|
+
"""Simple regex-based pattern."""
|
|
432
|
+
|
|
433
|
+
def __init__(
|
|
434
|
+
self,
|
|
435
|
+
vulnerability_id: str,
|
|
436
|
+
title: str,
|
|
437
|
+
description: str,
|
|
438
|
+
severity: str,
|
|
439
|
+
masvs_category: str,
|
|
440
|
+
masvs_control: str,
|
|
441
|
+
remediation: str,
|
|
442
|
+
cwe_id: str,
|
|
443
|
+
patterns: List[str],
|
|
444
|
+
false_positive_patterns: Optional[List[str]] = None,
|
|
445
|
+
context_false_positive_patterns: Optional[List[str]] = None
|
|
446
|
+
):
|
|
447
|
+
self.vulnerability_id = vulnerability_id
|
|
448
|
+
self.title = title
|
|
449
|
+
self.description = description
|
|
450
|
+
self.severity = severity
|
|
451
|
+
self.masvs_category = masvs_category
|
|
452
|
+
self.masvs_control = masvs_control
|
|
453
|
+
self.remediation = remediation
|
|
454
|
+
self.cwe_id = cwe_id
|
|
455
|
+
self.patterns = patterns
|
|
456
|
+
self.false_positive_patterns = false_positive_patterns or []
|
|
457
|
+
self.context_false_positive_patterns = context_false_positive_patterns or []
|
|
458
|
+
|
|
459
|
+
super().__init__()
|
|
460
|
+
|
|
461
|
+
self._fp_compiled = [
|
|
462
|
+
re.compile(p, re.MULTILINE | re.IGNORECASE)
|
|
463
|
+
for p in self.false_positive_patterns
|
|
464
|
+
]
|
|
465
|
+
self._context_fp_compiled = [
|
|
466
|
+
re.compile(p, re.MULTILINE | re.IGNORECASE)
|
|
467
|
+
for p in self.context_false_positive_patterns
|
|
468
|
+
]
|
|
469
|
+
|
|
470
|
+
def _is_false_positive(self, match: re.Match, content: str, lines: List[str], line_number: int) -> bool:
|
|
471
|
+
"""Check for false positives using two strategies:
|
|
472
|
+
|
|
473
|
+
1. LINE-LEVEL: Check the matched line against false_positive_patterns
|
|
474
|
+
(e.g., comment markers, placeholder text)
|
|
475
|
+
2. CONTEXT-LEVEL: Check surrounding lines (3 above, 1 below) against
|
|
476
|
+
context_false_positive_patterns (e.g., kDebugMode guard clauses)
|
|
477
|
+
|
|
478
|
+
Why context matters:
|
|
479
|
+
In Flutter/Dart, guard clauses like 'if (kDebugMode)' appear on the
|
|
480
|
+
line ABOVE the matched code. Checking only the matched line misses
|
|
481
|
+
these guards, causing false positives for V018 and V003.
|
|
482
|
+
"""
|
|
483
|
+
if super()._is_false_positive(match, content, lines, line_number):
|
|
484
|
+
return True
|
|
485
|
+
|
|
486
|
+
# Step 1: Check the MATCHED LINE against all FP patterns
|
|
487
|
+
line = lines[line_number - 1]
|
|
488
|
+
for fp_pattern in self._fp_compiled:
|
|
489
|
+
if fp_pattern.search(line):
|
|
490
|
+
return True
|
|
491
|
+
|
|
492
|
+
# Step 2: Check SURROUNDING CONTEXT against context FP patterns only
|
|
493
|
+
# Context window: 3 lines above + matched line + 1 line below
|
|
494
|
+
if self._context_fp_compiled:
|
|
495
|
+
context_start = max(0, line_number - 4)
|
|
496
|
+
context_end = min(len(lines), line_number + 1)
|
|
497
|
+
context_text = ' '.join(lines[context_start:context_end])
|
|
498
|
+
|
|
499
|
+
for fp_pattern in self._context_fp_compiled:
|
|
500
|
+
if fp_pattern.search(context_text):
|
|
501
|
+
return True
|
|
502
|
+
|
|
503
|
+
# Step 3: V001 value-shape gate.
|
|
504
|
+
# The name-based V001 patterns match on the identifier ("...password = ").
|
|
505
|
+
# Require the assigned string VALUE to actually look like a credential,
|
|
506
|
+
# otherwise it is a false positive (asset path, route, plain word, etc.).
|
|
507
|
+
# Matches with no quoted literal (sk-... / Bearer <jwt> patterns) are
|
|
508
|
+
# left untouched.
|
|
509
|
+
if self.vulnerability_id == 'V001':
|
|
510
|
+
literals = _extract_string_literals(match.group())
|
|
511
|
+
if literals and not any(looks_like_secret(lit) for lit in literals):
|
|
512
|
+
return True
|
|
513
|
+
|
|
514
|
+
return False
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MASVS-CODE Vulnerability Patterns
|
|
3
|
+
|
|
4
|
+
Patterns for detecting code quality and security vulnerabilities in Flutter/Dart code.
|
|
5
|
+
Maps to OWASP MASVS v2.1.0 CODE category.
|
|
6
|
+
|
|
7
|
+
Catalog Reference: V018-V021
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
CODE_PATTERNS = [
|
|
11
|
+
{
|
|
12
|
+
'vulnerability_id': 'V018',
|
|
13
|
+
'title': 'Debug Mode Enabled in Production',
|
|
14
|
+
'description': 'Debug flags or assertions left enabled in production builds. Exposes sensitive debugging information and may enable hidden functionality.',
|
|
15
|
+
'severity': 'medium',
|
|
16
|
+
'masvs_category': 'CODE',
|
|
17
|
+
'masvs_control': 'MASVS-CODE-4',
|
|
18
|
+
'cwe_id': 'CWE-489',
|
|
19
|
+
'remediation': 'Remove all debug code before release. Use kDebugMode/kReleaseMode flags to conditionally execute debug code. Verify build configuration excludes debug features.',
|
|
20
|
+
'patterns': [
|
|
21
|
+
# Actual debug-mode toggles left switched on. This rule targets debug
|
|
22
|
+
# FLAGS, not logging: plain debugPrint() calls are standard Flutter API
|
|
23
|
+
# usage and are covered (only when they leak sensitive data) by V003.
|
|
24
|
+
r'(?:debugMode|isDebug|isDebugMode|enableDebug|debugEnabled|devMode)\s*[:=]\s*true\b',
|
|
25
|
+
r'kDebugMode\s*\?\s*true',
|
|
26
|
+
r'(?:const|static|final|var)\s+(?:bool\s+)?(?:debugMode|isDebug|devMode)\s*=\s*true\b',
|
|
27
|
+
r'assert\s*\(\s*debugMode\s*==\s*true\s*\)',
|
|
28
|
+
# Genuine Flutter debug-rendering toggles left enabled
|
|
29
|
+
r'debug(?:Paint\w*|PrintRebuild\w*|PrintMarkNeedsLayout|RepaintRainbow)\s*=\s*true',
|
|
30
|
+
],
|
|
31
|
+
'false_positive_patterns': [
|
|
32
|
+
r'kDebugMode\s*\?\s*true',
|
|
33
|
+
],
|
|
34
|
+
'context_false_positive_patterns': [
|
|
35
|
+
r'if\s*\(\s*kDebugMode\s*\)',
|
|
36
|
+
r'kReleaseMode',
|
|
37
|
+
r'!kDebugMode',
|
|
38
|
+
]
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
'vulnerability_id': 'V019',
|
|
42
|
+
'title': 'SQL Injection Vulnerability',
|
|
43
|
+
'description': 'Building SQL queries through string concatenation with user input allows attackers to execute arbitrary SQL commands.',
|
|
44
|
+
'severity': 'critical',
|
|
45
|
+
'masvs_category': 'CODE',
|
|
46
|
+
'masvs_control': 'MASVS-CODE-4',
|
|
47
|
+
'cwe_id': 'CWE-89',
|
|
48
|
+
'remediation': 'Use parameterized queries or prepared statements. Never concatenate user input into SQL strings. Use ORM libraries like Drift (formerly Moor).',
|
|
49
|
+
'patterns': [
|
|
50
|
+
r'rawQuery\s*\(\s*["\'][^"\']*\$',
|
|
51
|
+
r'rawQuery\s*\(\s*["\'][^"\']*\+',
|
|
52
|
+
r'(?:rawDelete|rawInsert|rawUpdate)\s*\(\s*["\'][^"\']*\$',
|
|
53
|
+
r'(?:rawDelete|rawInsert|rawUpdate)\s*\(\s*["\'][^"\']*\+',
|
|
54
|
+
r'execute\s*\(\s*["\'](?:SELECT|INSERT|UPDATE|DELETE)[^"\']*\$',
|
|
55
|
+
r'db\.execute\s*\(\s*["\'][^"\']*\+',
|
|
56
|
+
],
|
|
57
|
+
'false_positive_patterns': [
|
|
58
|
+
r'rawQuery\s*\(\s*["\'][^"\']*\?\s*["\']',
|
|
59
|
+
r'parameterized',
|
|
60
|
+
r'preparedStatement',
|
|
61
|
+
]
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
'vulnerability_id': 'V020',
|
|
65
|
+
'title': 'Vulnerable Third-Party Dependencies',
|
|
66
|
+
'description': 'Using third-party packages with known security vulnerabilities. Outdated dependencies may contain exploitable security flaws.',
|
|
67
|
+
'severity': 'medium',
|
|
68
|
+
'masvs_category': 'CODE',
|
|
69
|
+
'masvs_control': 'MASVS-CODE-3',
|
|
70
|
+
'cwe_id': 'CWE-1104',
|
|
71
|
+
'remediation': 'Regularly update dependencies. Use `flutter pub outdated` to check for updates. Subscribe to security advisories for critical packages. Implement dependency scanning in CI/CD.',
|
|
72
|
+
'patterns': [
|
|
73
|
+
# Applied to pubspec.yaml (see SecurityScanner.CONFIG_FILE_RULES).
|
|
74
|
+
# The lookbehind stops matches inside longer package names,
|
|
75
|
+
# e.g. 'rhttp: ^0.18.0' is a different package from 'http'.
|
|
76
|
+
r'(?<![\w-])http:\s*\^\s*0\.[0-9]', # Very old http package
|
|
77
|
+
r'(?<![\w-])dio:\s*\^\s*[0-3]\.', # Old dio versions
|
|
78
|
+
r'(?<![\w-])webview_flutter:\s*\^\s*[0-2]\.', # Old webview
|
|
79
|
+
],
|
|
80
|
+
'false_positive_patterns': []
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
'vulnerability_id': 'V021',
|
|
84
|
+
'title': 'Outdated Minimum SDK Version',
|
|
85
|
+
'description': 'App supports outdated Android/iOS versions with known security vulnerabilities. Old platform versions lack modern security features.',
|
|
86
|
+
'severity': 'medium',
|
|
87
|
+
'masvs_category': 'CODE',
|
|
88
|
+
'masvs_control': 'MASVS-CODE-1',
|
|
89
|
+
'cwe_id': 'CWE-1104',
|
|
90
|
+
'remediation': 'Set minSdkVersion to at least 23 (Android 6.0) for modern security features. For iOS, target iOS 12.0 or higher. Consider security implications of supporting older versions.',
|
|
91
|
+
'patterns': [
|
|
92
|
+
# Applied to android/app/build.gradle(.kts) and ios/Podfile
|
|
93
|
+
# (see SecurityScanner.CONFIG_FILE_RULES)
|
|
94
|
+
r'minSdkVersion\s+(?:1[0-9]|2[0-2])\b', # Android SDK < 23
|
|
95
|
+
r'minSdk\s*=\s*(?:1[0-9]|2[0-2])\b',
|
|
96
|
+
r"platform\s*:ios\s*,\s*['\"](?:[0-9]|1[0-1])\.", # iOS < 12
|
|
97
|
+
],
|
|
98
|
+
'false_positive_patterns': [
|
|
99
|
+
r'minSdkVersion\s+(?:2[3-9]|[3-9][0-9])',
|
|
100
|
+
r'minSdk\s*=\s*(?:2[3-9]|[3-9][0-9])',
|
|
101
|
+
]
|
|
102
|
+
},
|
|
103
|
+
]
|