-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathextension-security.js
More file actions
331 lines (281 loc) · 10 KB
/
Copy pathextension-security.js
File metadata and controls
331 lines (281 loc) · 10 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
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
class ExtensionSecurity {
constructor() {
this.permissionRequests = new Map();
this.grantedPermissions = new Map();
this.securityPolicies = this.initializeSecurityPolicies();
}
initializeSecurityPolicies() {
return {
// Allowed permissions for extensions
allowedPermissions: [
'tabs',
'storage',
'contextMenus',
'browserAction',
'activeTab',
'background',
'notifications',
'bookmarks',
'history'
],
// Dangerous permissions that require explicit user consent
dangerousPermissions: [
'webRequest',
'webRequestBlocking',
'proxy',
'privacy',
'management',
'nativeMessaging',
'debugger'
],
// Blocked permissions that are never allowed
blockedPermissions: [
'experimental',
'system.cpu',
'system.memory',
'system.storage',
'fileSystem',
'serial',
'usb',
'bluetooth'
],
// Content Security Policy for extension pages
extensionCSP: "default-src 'self'; script-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline';",
// Maximum file sizes
maxManifestSize: 1024 * 1024, // 1MB
maxExtensionSize: 50 * 1024 * 1024, // 50MB
maxFileCount: 1000
};
}
validateManifest(manifest, extensionPath) {
const errors = [];
const warnings = [];
try {
// Basic structure validation
if (!manifest.name || typeof manifest.name !== 'string') {
errors.push('Extension name is required and must be a string');
}
if (!manifest.version || typeof manifest.version !== 'string') {
errors.push('Extension version is required and must be a string');
}
if (!manifest.manifest_version || ![2, 3].includes(manifest.manifest_version)) {
errors.push('Manifest version must be 2 or 3');
}
// Validate permissions
if (manifest.permissions) {
if (!Array.isArray(manifest.permissions)) {
errors.push('Permissions must be an array');
} else {
const invalidPermissions = this.validatePermissions(manifest.permissions);
if (invalidPermissions.length > 0) {
errors.push(`Invalid permissions: ${invalidPermissions.join(', ')}`);
}
}
}
// Validate content scripts
if (manifest.content_scripts) {
if (!Array.isArray(manifest.content_scripts)) {
errors.push('Content scripts must be an array');
} else {
manifest.content_scripts.forEach((script, index) => {
if (!script.matches || !Array.isArray(script.matches)) {
errors.push(`Content script ${index} must have matches array`);
}
if (!script.js && !script.css) {
errors.push(`Content script ${index} must have js or css files`);
}
});
}
}
// Validate background scripts
if (manifest.background) {
if (manifest.manifest_version === 2) {
if (!manifest.background.scripts && !manifest.background.page) {
warnings.push('Background page should specify scripts or page');
}
} else if (manifest.manifest_version === 3) {
if (!manifest.background.service_worker) {
warnings.push('Manifest v3 should use service_worker for background');
}
}
}
// Validate web accessible resources
if (manifest.web_accessible_resources) {
if (manifest.manifest_version === 2) {
if (!Array.isArray(manifest.web_accessible_resources)) {
errors.push('Web accessible resources must be an array in manifest v2');
}
} else if (manifest.manifest_version === 3) {
if (!Array.isArray(manifest.web_accessible_resources)) {
errors.push('Web accessible resources must be an array in manifest v3');
} else {
manifest.web_accessible_resources.forEach((resource, index) => {
if (!resource.resources || !resource.matches) {
errors.push(`Web accessible resource ${index} must have resources and matches`);
}
});
}
}
}
// Check file size limits
const extensionSize = this.calculateDirectorySize(extensionPath);
if (extensionSize > this.securityPolicies.maxExtensionSize) {
errors.push(`Extension size (${extensionSize} bytes) exceeds maximum allowed size`);
}
// Check file count
const fileCount = this.countFiles(extensionPath);
if (fileCount > this.securityPolicies.maxFileCount) {
errors.push(`Extension has too many files (${fileCount}), maximum allowed is ${this.securityPolicies.maxFileCount}`);
}
return {
valid: errors.length === 0,
errors,
warnings,
permissions: manifest.permissions || [],
dangerousPermissions: this.getDangerousPermissions(manifest.permissions || [])
};
} catch (error) {
return {
valid: false,
errors: [`Manifest validation failed: ${error.message}`],
warnings: [],
permissions: [],
dangerousPermissions: []
};
}
}
validatePermissions(permissions) {
const invalid = [];
permissions.forEach(permission => {
// Check if permission is blocked
if (this.securityPolicies.blockedPermissions.includes(permission)) {
invalid.push(permission);
return;
}
// Check if permission is in allowed or dangerous list
const isAllowed = this.securityPolicies.allowedPermissions.includes(permission);
const isDangerous = this.securityPolicies.dangerousPermissions.includes(permission);
// Allow URL patterns for host permissions
const isHostPermission = permission.includes('://') || permission.startsWith('<all_urls>');
if (!isAllowed && !isDangerous && !isHostPermission) {
invalid.push(permission);
}
});
return invalid;
}
getDangerousPermissions(permissions) {
return permissions.filter(permission =>
this.securityPolicies.dangerousPermissions.includes(permission)
);
}
async requestPermissions(extensionId, permissions, userCallback) {
const dangerousPermissions = this.getDangerousPermissions(permissions);
if (dangerousPermissions.length === 0) {
// Auto-grant safe permissions
this.grantPermissions(extensionId, permissions);
return { granted: true, permissions };
}
// Request user consent for dangerous permissions
const requestId = crypto.randomUUID();
this.permissionRequests.set(requestId, {
extensionId,
permissions: dangerousPermissions,
callback: userCallback,
timestamp: Date.now()
});
return {
granted: false,
requestId,
dangerousPermissions,
message: 'User consent required for dangerous permissions'
};
}
grantPermissions(extensionId, permissions) {
if (!this.grantedPermissions.has(extensionId)) {
this.grantedPermissions.set(extensionId, new Set());
}
const extensionPermissions = this.grantedPermissions.get(extensionId);
permissions.forEach(permission => extensionPermissions.add(permission));
console.log(`✅ Granted permissions to ${extensionId}:`, permissions);
}
revokePermissions(extensionId, permissions = null) {
if (permissions === null) {
// Revoke all permissions
this.grantedPermissions.delete(extensionId);
} else {
const extensionPermissions = this.grantedPermissions.get(extensionId);
if (extensionPermissions) {
permissions.forEach(permission => extensionPermissions.delete(permission));
}
}
}
hasPermission(extensionId, permission) {
const extensionPermissions = this.grantedPermissions.get(extensionId);
return extensionPermissions ? extensionPermissions.has(permission) : false;
}
sanitizeExtensionContent(content, contentType = 'html') {
// Basic content sanitization
if (contentType === 'html') {
// Remove dangerous script tags and event handlers
content = content.replace(/<script[^>]*>.*?<\/script>/gis, '');
content = content.replace(/on\w+\s*=\s*["'][^"']*["']/gi, '');
content = content.replace(/javascript:/gi, '');
}
return content;
}
generateExtensionCSP(extensionId) {
// Generate Content Security Policy for extension
return this.securityPolicies.extensionCSP.replace(
"'self'",
`'self' chrome-extension://${extensionId}`
);
}
calculateDirectorySize(dirPath) {
let totalSize = 0;
try {
const files = fs.readdirSync(dirPath, { withFileTypes: true });
for (const file of files) {
const filePath = path.join(dirPath, file.name);
if (file.isDirectory()) {
totalSize += this.calculateDirectorySize(filePath);
} else {
const stats = fs.statSync(filePath);
totalSize += stats.size;
}
}
} catch (error) {
console.error('Error calculating directory size:', error);
}
return totalSize;
}
countFiles(dirPath) {
let fileCount = 0;
try {
const files = fs.readdirSync(dirPath, { withFileTypes: true });
for (const file of files) {
const filePath = path.join(dirPath, file.name);
if (file.isDirectory()) {
fileCount += this.countFiles(filePath);
} else {
fileCount++;
}
}
} catch (error) {
console.error('Error counting files:', error);
}
return fileCount;
}
cleanupExpiredRequests() {
const now = Date.now();
const expiredTime = 5 * 60 * 1000; // 5 minutes
for (const [requestId, request] of this.permissionRequests) {
if (now - request.timestamp > expiredTime) {
this.permissionRequests.delete(requestId);
}
}
}
}
module.exports = ExtensionSecurity;