Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
558 lines (473 loc) · 21.6 KB
/
Copy pathscript.js
File metadata and controls
558 lines (473 loc) · 21.6 KB
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
// DOM Elements
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');
const fileName = document.getElementById('fileName');
const removeFile = document.getElementById('removeFile');
const scanButton = document.getElementById('scanButton');
const resultsSection = document.getElementById('resultsSection');
// Mock data for demo purposes
const mockScenarios = [
{
appName: "PhonePe Pro",
imitatedBrand: "PhonePe",
uiSimilarity: 94,
permissionRisk: "high",
riskScore: 8.7,
decision: "blocked",
explanation: "This application exhibits extremely high UI similarity (94%) to the legitimate PhonePe app, suggesting a sophisticated phishing attempt. The app requests dangerous permissions including SMS access, contact list access, and device admin privileges that are unnecessary for a payment app. The certificate signature does not match the official PhonePe developer. Our AI model detected pixel-perfect cloning of login screens and payment interfaces designed to harvest user credentials and financial information."
},
{
appName: "Google Pay Lite",
imitatedBrand: "Google Pay",
uiSimilarity: 87,
permissionRisk: "high",
riskScore: 8.2,
decision: "blocked",
explanation: "This fraudulent application mimics Google Pay's interface with 87% similarity. Analysis reveals unauthorized use of Google's brand assets and color schemes. The app requests excessive permissions including camera, microphone, and location tracking that exceed normal payment app requirements. The package name 'com.gpaylite.unofficial' and mismatched developer certificate are red flags. Our deep learning model identified cloned UPI transaction screens designed to intercept payment credentials."
},
{
appName: "Paytm Cashback",
imitatedBrand: "Paytm",
uiSimilarity: 91,
permissionRisk: "high",
riskScore: 9.1,
decision: "blocked",
explanation: "Critical threat detected. This malicious app shows 91% UI similarity to official Paytm, using identical color schemes, logos, and interface elements. It requests dangerous permissions including SMS interception, call logs, and storage access to steal OTPs and personal data. The developer certificate is fraudulent and the app contains obfuscated code designed to evade detection. Our AI identified cloned wallet screens and fake cashback offers designed to trick users into entering banking credentials."
},
{
appName: "BHIM UPI Fast",
imitatedBrand: "BHIM",
uiSimilarity: 78,
permissionRisk: "medium",
riskScore: 6.8,
decision: "blocked",
explanation: "This application attempts to impersonate BHIM UPI with 78% interface similarity. While not a perfect clone, it uses similar branding elements and color schemes to deceive users. The app requests medium-risk permissions including contacts and SMS access. The developer signature doesn't match NPCI (National Payments Corporation of India), the official BHIM developer. Our model detected suspicious network activity patterns and cloned UPI PIN entry screens that could compromise user security."
},
{
appName: "Calculator Pro",
imitatedBrand: "None",
uiSimilarity: 12,
permissionRisk: "low",
riskScore: 1.8,
decision: "safe",
explanation: "This application passed all security checks. It shows minimal similarity to known banking or payment apps and does not attempt brand impersonation. The requested permissions (basic storage and display) are appropriate for a calculator application. The developer certificate is valid and the app's behavior matches its stated functionality. Our AI model found no suspicious UI patterns, no hidden payment screens, and no malicious code. The app is safe to install."
},
{
appName: "Fitness Tracker",
imitatedBrand: "None",
uiSimilarity: 8,
permissionRisk: "low",
riskScore: 2.1,
decision: "safe",
explanation: "Security analysis complete: This fitness tracking application is legitimate. It shows no similarity to financial apps and doesn't mimic any known banking brands. The requested permissions (location, activity recognition, sensors) are standard for fitness apps. The developer has a verified certificate and the app's code is transparent with no obfuscation. Our AI detected no fraudulent UI patterns or hidden functionality. The app poses no security risk and is safe for installation."
}
];
let selectedFile = null;
// Event Listeners
uploadArea.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', handleFileSelect);
removeFile.addEventListener('click', handleFileRemove);
scanButton.addEventListener('click', handleScan);
// Drag and Drop
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('drag-over');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('drag-over');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('drag-over');
const files = e.dataTransfer.files;
if (files.length > 0) {
const file = files[0];
if (file.name.endsWith('.apk') || file.name.endsWith('.json')) {
selectedFile = file;
displayFileInfo(file);
}
}
});
// Demo Mode Functionality
const demoModeToggle = document.getElementById('demoModeToggle');
const demoButtons = document.getElementById('demoButtons');
const demoBlockedBtn = document.getElementById('demoBlocked');
const demoSafeBtn = document.getElementById('demoSafe');
// Predefined test cases
const DEMO_TEST_CASES = {
blocked: {
app_name: "PhonePe Pro",
package_name: "com.phonepe.unofficial",
permissions: ["READ_SMS", "RECEIVE_SMS", "READ_CONTACTS", "ACCESSIBILITY_SERVICE"],
declared_brand: "PhonePe",
app_icon_image: null
},
safe: {
app_name: "Simple Calculator",
package_name: "com.calculator.simple",
permissions: ["INTERNET"],
declared_brand: null,
app_icon_image: null
}
};
// Toggle demo mode
demoModeToggle.addEventListener('change', (e) => {
if (e.target.checked) {
demoButtons.style.display = 'flex';
} else {
demoButtons.style.display = 'none';
}
});
// Demo: Fake PhonePe (BLOCKED)
demoBlockedBtn.addEventListener('click', async () => {
await runDemoTest(DEMO_TEST_CASES.blocked, 'Fake PhonePe App');
});
// Demo: Safe App (SAFE)
demoSafeBtn.addEventListener('click', async () => {
await runDemoTest(DEMO_TEST_CASES.safe, 'Simple Calculator');
});
// Run demo test
async function runDemoTest(metadata, displayName) {
// Show loading state
const buttonText = scanButton.querySelector('.button-text');
const buttonLoader = scanButton.querySelector('.button-loader');
buttonText.style.display = 'none';
buttonLoader.style.display = 'flex';
scanButton.disabled = true;
try {
// Simulate analysis delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Analyze metadata
const analysis = analyzeMetadata(metadata);
// Display results
displayResults(analysis);
// Show results section
resultsSection.style.display = 'block';
resultsSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
console.log(`Demo Test: ${displayName}`, analysis);
} catch (error) {
alert('Error running demo: ' + error.message);
console.error('Demo error:', error);
} finally {
// Reset button
buttonText.style.display = 'block';
buttonLoader.style.display = 'none';
scanButton.disabled = false;
}
}
// File Handling
function handleFileSelect(e) {
const file = e.target.files[0];
if (file) {
selectedFile = file;
displayFileInfo(file);
}
}
function displayFileInfo(file) {
fileName.textContent = file.name;
uploadArea.style.display = 'none';
fileInfo.style.display = 'flex';
scanButton.disabled = false;
}
function handleFileRemove(e) {
e.stopPropagation();
selectedFile = null;
fileInput.value = '';
uploadArea.style.display = 'flex';
fileInfo.style.display = 'none';
scanButton.disabled = true;
resultsSection.style.display = 'none';
}
// Metadata Extraction
async function extractMetadata(file) {
const fileName = file.name.toLowerCase();
if (fileName.endsWith('.json')) {
// Read JSON file directly
return await readJSONMetadata(file);
} else if (fileName.endsWith('.apk')) {
// Simulate APK metadata extraction
return await simulateAPKMetadata(file);
}
throw new Error('Unsupported file type');
}
async function readJSONMetadata(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const metadata = JSON.parse(e.target.result);
// Validate required fields
if (!metadata.app_name || !metadata.package_name) {
reject(new Error('Invalid JSON: missing required fields (app_name, package_name)'));
return;
}
// Ensure permissions is an array
if (!Array.isArray(metadata.permissions)) {
metadata.permissions = [];
}
resolve(metadata);
} catch (error) {
reject(new Error('Invalid JSON file: ' + error.message));
}
};
reader.onerror = () => reject(new Error('Failed to read file'));
reader.readAsText(file);
});
}
async function simulateAPKMetadata(file) {
// Simulate APK parsing delay
await new Promise(resolve => setTimeout(resolve, 1000));
// Generate simulated metadata based on file name
const fileName = file.name.replace('.apk', '');
// Simulate different app scenarios based on filename patterns
const metadata = {
app_name: fileName,
package_name: `com.${fileName.toLowerCase().replace(/\s+/g, '.')}.app`,
permissions: [],
app_icon_image: null,
declared_brand: null
};
// Detect potential fraud patterns in filename
if (fileName.toLowerCase().includes('phonepe')) {
metadata.app_name = 'PhonePe Pro';
metadata.package_name = 'com.phonepe.unofficial';
metadata.permissions = ['READ_SMS', 'RECEIVE_SMS', 'READ_CONTACTS', 'CAMERA', 'ACCESS_FINE_LOCATION'];
metadata.declared_brand = 'PhonePe';
} else if (fileName.toLowerCase().includes('googlepay') || fileName.toLowerCase().includes('gpay')) {
metadata.app_name = 'Google Pay Lite';
metadata.package_name = 'com.gpaylite.unofficial';
metadata.permissions = ['READ_SMS', 'CAMERA', 'RECORD_AUDIO', 'ACCESS_FINE_LOCATION'];
metadata.declared_brand = 'Google Pay';
} else if (fileName.toLowerCase().includes('paytm')) {
metadata.app_name = 'Paytm Cashback';
metadata.package_name = 'com.paytm.cashback.fake';
metadata.permissions = ['READ_SMS', 'RECEIVE_SMS', 'READ_CALL_LOG', 'READ_CONTACTS', 'WRITE_EXTERNAL_STORAGE'];
metadata.declared_brand = 'Paytm';
} else if (fileName.toLowerCase().includes('bhim') || fileName.toLowerCase().includes('upi')) {
metadata.app_name = 'BHIM UPI Fast';
metadata.package_name = 'com.bhim.upi.fast';
metadata.permissions = ['READ_SMS', 'READ_CONTACTS', 'CAMERA'];
metadata.declared_brand = 'BHIM';
} else {
// Safe app scenario
metadata.permissions = ['INTERNET', 'ACCESS_NETWORK_STATE'];
}
return metadata;
}
// AI Analysis Workflow
function analyzeMetadata(metadata) {
const analysis = {
appName: metadata.app_name,
imitatedBrand: 'None',
uiSimilarity: 0,
permissionRisk: 'low',
permissionRiskScore: 0,
riskScore: 0,
finalRiskScore: 0,
decision: 'safe',
explanation: '',
permissionAnalysis: null,
visualAnalysis: null
};
// Analyze permissions with Indian financial fraud focus
const permissionAnalysis = analyzePermissions(metadata.permissions);
analysis.permissionAnalysis = permissionAnalysis;
analysis.permissionRisk = permissionAnalysis.permission_risk_level.toLowerCase();
analysis.permissionRiskScore = permissionAnalysis.permission_risk_score;
// Perform visual similarity analysis
const visualAnalysis = analyzeVisualSimilarity(metadata);
analysis.visualAnalysis = visualAnalysis;
analysis.imitatedBrand = visualAnalysis.matched_brand;
analysis.uiSimilarity = visualAnalysis.ui_similarity_percentage;
// Check for brand impersonation based on visual analysis
const isBrandImpersonation = visualAnalysis.impersonation_flag;
// Calculate Final Risk Score using weighted formula
// Final Risk = (0.6 × Permission Risk Score) + (0.4 × UI Similarity Percentage)
const finalRiskScore = (0.6 * analysis.permissionRiskScore) + (0.4 * analysis.uiSimilarity);
analysis.finalRiskScore = Math.round(finalRiskScore * 10) / 10; // Round to 1 decimal place
// Make decision based on threshold
// If Final Risk ≥ 70 → BLOCK, Else → ALLOW
if (analysis.finalRiskScore >= 70) {
analysis.decision = 'blocked';
} else {
analysis.decision = 'safe';
}
// Legacy risk score (0-10) for UI display compatibility
analysis.riskScore = (analysis.finalRiskScore / 10).toFixed(1);
// Generate explanation
analysis.explanation = generateExplanation(metadata, analysis, permissionAnalysis, visualAnalysis);
// Log final risk calculation for debugging
console.log('Final Risk Calculation:', {
permission_risk_score: analysis.permissionRiskScore,
ui_similarity_percentage: analysis.uiSimilarity,
final_risk_score: analysis.finalRiskScore,
final_decision: analysis.decision.toUpperCase()
});
return analysis;
}
// Permission Analysis for Indian Financial Fraud Detection
function analyzePermissions(permissions) {
// High-risk permissions commonly used in Indian financial fraud
const highRiskPermissions = [
'READ_SMS',
'RECEIVE_SMS',
'READ_CONTACTS',
'ACCESSIBILITY_SERVICE',
'REQUEST_INSTALL_PACKAGES',
'DEVICE_ADMIN',
'READ_CALL_LOG'
];
// Additional dangerous permissions
const additionalDangerousPermissions = [
'SEND_SMS',
'WRITE_CALL_LOG',
'WRITE_CONTACTS',
'CAMERA',
'RECORD_AUDIO',
'ACCESS_FINE_LOCATION',
'ACCESS_COARSE_LOCATION',
'WRITE_EXTERNAL_STORAGE',
'READ_EXTERNAL_STORAGE',
'GET_ACCOUNTS',
'USE_CREDENTIALS',
'BIND_DEVICE_ADMIN',
'SYSTEM_ALERT_WINDOW'
];
// Count high-risk permissions
const highRiskFound = permissions.filter(p => highRiskPermissions.includes(p));
const additionalDangerousFound = permissions.filter(p =>
additionalDangerousPermissions.includes(p) && !highRiskPermissions.includes(p)
);
// Only count high-risk permissions as per requirement
const dangerousPermissionCount = highRiskFound.length;
// Calculate permission risk score (0-100)
let permissionRiskScore = 0;
// High-risk permissions: 20 points each (max 140, capped at 100)
permissionRiskScore += highRiskFound.length * 20;
// Additional dangerous permissions: 5 points each
permissionRiskScore += additionalDangerousFound.length * 5;
// Cap at 100
permissionRiskScore = Math.min(100, permissionRiskScore);
// Determine risk level
let permissionRiskLevel;
if (permissionRiskScore >= 60) {
permissionRiskLevel = 'HIGH';
} else if (permissionRiskScore >= 30) {
permissionRiskLevel = 'MEDIUM';
} else {
permissionRiskLevel = 'LOW';
}
// Return JSON structure
const analysis = {
dangerous_permission_count: dangerousPermissionCount,
permission_risk_score: permissionRiskScore,
permission_risk_level: permissionRiskLevel,
high_risk_permissions_found: highRiskFound,
additional_dangerous_permissions: additionalDangerousFound
};
// Log the analysis for debugging
console.log('Permission Analysis:', JSON.stringify(analysis, null, 2));
return analysis;
}
function generateExplanation(metadata, analysis, permissionAnalysis, visualAnalysis) {
const highRiskPerms = permissionAnalysis.high_risk_permissions_found;
const allDangerousPerms = [...permissionAnalysis.high_risk_permissions_found, ...permissionAnalysis.additional_dangerous_permissions];
if (analysis.decision === 'blocked') {
// BLOCKED - Simple explanation for non-technical users
let explanation = '⚠️ यह ऐप खतरनाक है। ';
// Explain impersonation in simple terms
if (visualAnalysis.impersonation_flag) {
explanation += `यह ${visualAnalysis.matched_brand} की नकल करके आपको धोखा देने की कोशिश कर रहा है। `;
}
// Explain dangerous permissions
if (highRiskPerms.length > 0) {
explanation += `यह आपके SMS, contacts और अन्य निजी जानकारी को चुरा सकता है। `;
} else if (allDangerousPerms.length > 0) {
explanation += `यह आपकी निजी जानकारी को access कर सकता है। `;
}
// What could happen
explanation += `अगर आप इसे install करते हैं तो आपके बैंक account से पैसे चोरी हो सकते हैं या आपकी OTP और password चोरी हो सकते हैं।`;
return explanation;
} else {
// SAFE - Simple reassurance for users
let explanation = '✅ यह ऐप सुरक्षित है। ';
// Explain why it's safe
if (visualAnalysis.matched_brand === 'None') {
explanation += 'यह किसी बैंक या payment app की नकल नहीं कर रहा है। ';
}
if (allDangerousPerms.length === 0) {
explanation += 'इसमें कोई खतरनाक permissions नहीं हैं। ';
} else {
explanation += 'इसके permissions सामान्य हैं और इसके काम के लिए जरूरी हैं। ';
}
explanation += 'आप इसे बिना किसी चिंता के install कर सकते हैं।';
return explanation;
}
}
// Scan Functionality
async function handleScan() {
if (!selectedFile) return;
// Show loading state
const buttonText = scanButton.querySelector('.button-text');
const buttonLoader = scanButton.querySelector('.button-loader');
buttonText.style.display = 'none';
buttonLoader.style.display = 'flex';
scanButton.disabled = true;
try {
// Extract metadata from file
const metadata = await extractMetadata(selectedFile);
// Simulate AI analysis delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Analyze metadata with AI workflow
const analysis = analyzeMetadata(metadata);
// Display results
displayResults(analysis);
// Scroll to results
resultsSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
} catch (error) {
alert('Error scanning file: ' + error.message);
console.error('Scan error:', error);
} finally {
// Reset button
buttonText.style.display = 'block';
buttonLoader.style.display = 'none';
scanButton.disabled = false;
}
}
function displayResults(data) {
// Show results section
resultsSection.style.display = 'block';
// Populate data
document.getElementById('appName').textContent = data.appName;
document.getElementById('imitatedBrand').textContent = data.imitatedBrand;
// UI Similarity with animation
const similarityFill = document.getElementById('similarityFill');
const similarityText = document.getElementById('similarityText');
setTimeout(() => {
similarityFill.style.width = data.uiSimilarity + '%';
similarityText.textContent = data.uiSimilarity + '%';
}, 100);
// Permission Risk with score
const permissionRisk = document.getElementById('permissionRisk');
permissionRisk.textContent = `${data.permissionRisk.toUpperCase()} (${data.permissionRiskScore}/100)`;
permissionRisk.className = 'risk-badge ' + data.permissionRisk;
// Final Risk Score (0-100 scale)
const riskScoreElement = document.getElementById('riskScore');
if (data.finalRiskScore !== undefined) {
riskScoreElement.textContent = `${data.finalRiskScore} / 100`;
} else {
// Fallback to legacy score
riskScoreElement.textContent = data.riskScore + ' / 10';
}
// Decision Badge
const decisionBadge = document.getElementById('decisionBadge');
decisionBadge.textContent = data.decision === 'blocked' ? '🚫 BLOCKED' : '✓ SAFE';
decisionBadge.className = 'decision-badge ' + data.decision;
// Explanation
document.getElementById('explanationText').textContent = data.explanation;
}
// Initialize
document.addEventListener('DOMContentLoaded', () => {
console.log('AppShield AI - Fraud App Detector initialized');
});