-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcontextAnalyzer.js
609 lines (513 loc) · 17.9 KB
/
contextAnalyzer.js
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
class ContextAnalyzer {
constructor() {
// 定义不同上下文的特征模式
this.contexts = {
html: {
patterns: [
/<[^>]*>/g, // HTML标签
/&[a-zA-Z]+;/g, // HTML实体
/&#x?[0-9a-fA-F]+;/g // HTML数字实体
],
attributes: [
'href', 'src', 'onerror', 'onload', 'onclick',
'onmouseover', 'onmouseout', 'onkeypress',
'onkeydown', 'onkeyup', 'onfocus', 'onblur'
]
},
javascript: {
patterns: [
/<script[^>]*>[\s\S]*?<\/script>/gi, // 脚本标签
/javascript:/i, // JavaScript协议
/on\w+\s*=/i, // 事件处理器
/eval\s*\(/i, // eval函数
/Function\s*\(/i, // Function构造函数
/setTimeout\s*\(/i, // setTimeout
/setInterval\s*\(/i // setInterval
],
attributes: [
'onerror', 'onload', 'onclick', 'onmouseover',
'onmouseout', 'onkeypress', 'onkeydown', 'onkeyup'
]
},
css: {
patterns: [
/<style[^>]*>[\s\S]*?<\/style>/gi, // 样式标签
/style\s*=\s*["'][^"']*["']/i, // 内联样式
/url\s*\(/i, // url()函数
/expression\s*\(/i, // expression()函数
/@import/i // @import规则
],
attributes: ['style']
}
};
// 定义常见的净化方法
this.sanitizationMethods = {
html: {
patterns: [
/htmlspecialchars/i,
/htmlentities/i,
/strip_tags/i,
/sanitize/i
],
functions: [
'escapeHTML',
'sanitizeHTML',
'cleanHTML',
'purifyHTML'
]
},
javascript: {
patterns: [
/escape\s*\(/i,
/encodeURI\s*\(/i,
/encodeURIComponent\s*\(/i,
/sanitize\s*\(/i
],
functions: [
'escapeJS',
'sanitizeJS',
'cleanJS',
'purifyJS'
]
},
css: {
patterns: [
/sanitize\s*\(/i,
/clean\s*\(/i,
/purify\s*\(/i
],
functions: [
'sanitizeCSS',
'cleanCSS',
'purifyCSS'
]
}
};
}
// 分析上下文
analyzeContext(element) {
const analysis = {
type: null,
location: null,
sanitization: null,
encoding: null,
parentContext: null,
recommendations: []
};
// 检测上下文类型
analysis.type = this.detectContextType(element);
// 分析位置
analysis.location = this.analyzeLocation(element);
// 检测净化方法
analysis.sanitization = this.detectSanitization(element);
// 分析编码
analysis.encoding = this.analyzeEncoding(element);
// 分析父上下文
analysis.parentContext = this.analyzeParentContext(element);
// 生成建议
analysis.recommendations = this.generateRecommendations(analysis);
return analysis;
}
// 检测上下文类型
detectContextType(element) {
const types = [];
// 检查HTML上下文
if (this.checkHTMLContext(element)) {
types.push('html');
}
// 检查JavaScript上下文
if (this.checkJavaScriptContext(element)) {
types.push('javascript');
}
// 检查CSS上下文
if (this.checkCSSContext(element)) {
types.push('css');
}
return types;
}
// 检查HTML上下文
checkHTMLContext(element) {
const htmlContext = this.contexts.html;
// 检查标签名
if (htmlContext.attributes.includes(element.tagName?.toLowerCase())) {
return true;
}
// 检查属性
for (const attr of htmlContext.attributes) {
if (element.hasAttribute(attr)) {
return true;
}
}
// 检查内容模式
const content = element.innerHTML || element.textContent;
for (const pattern of htmlContext.patterns) {
if (pattern.test(content)) {
return true;
}
}
return false;
}
// 检查JavaScript上下文
checkJavaScriptContext(element) {
const jsContext = this.contexts.javascript;
// 检查脚本标签
if (element.tagName?.toLowerCase() === 'script') {
return true;
}
// 检查事件处理器
for (const attr of jsContext.attributes) {
if (element.hasAttribute(attr)) {
return true;
}
}
// 检查内容模式
const content = element.innerHTML || element.textContent;
for (const pattern of jsContext.patterns) {
if (pattern.test(content)) {
return true;
}
}
return false;
}
// 检查CSS上下文
checkCSSContext(element) {
const cssContext = this.contexts.css;
// 检查样式标签
if (element.tagName?.toLowerCase() === 'style') {
return true;
}
// 检查样式属性
if (element.hasAttribute('style')) {
return true;
}
// 检查内容模式
const content = element.innerHTML || element.textContent;
for (const pattern of cssContext.patterns) {
if (pattern.test(content)) {
return true;
}
}
return false;
}
// 分析位置
analyzeLocation(element) {
const location = {
tagName: element.tagName?.toLowerCase(),
attributeName: null,
parentTag: null,
domPath: this.generateDOMPath(element),
id: element.id,
class: element.className
};
// 获取属性名
for (const attr of element.attributes) {
if (this.isInjectableAttribute(attr.name)) {
location.attributeName = attr.name;
break;
}
}
// 获取父标签
if (element.parentElement) {
location.parentTag = element.parentElement.tagName?.toLowerCase();
}
return location;
}
// 生成DOM路径
generateDOMPath(element) {
const path = [];
let current = element;
while (current && current.tagName) {
let selector = current.tagName.toLowerCase();
// 添加ID选择器
if (current.id) {
selector += `#${current.id}`;
}
// 添加类选择器
if (current.className) {
selector += `.${current.className.split(' ').join('.')}`;
}
path.unshift(selector);
current = current.parentElement;
}
return path.join(' > ');
}
// 检查可注入属性
isInjectableAttribute(attrName) {
const injectableAttrs = [
'href', 'src', 'onerror', 'onload', 'onclick',
'onmouseover', 'onmouseout', 'onkeypress',
'onkeydown', 'onkeyup', 'onfocus', 'onblur',
'style', 'data-*'
];
return injectableAttrs.some(attr =>
attrName.toLowerCase() === attr ||
attrName.toLowerCase().startsWith('data-')
);
}
// 检测净化方法
detectSanitization(element) {
const sanitization = {
detected: false,
methods: [],
effectiveness: null
};
// 检查HTML净化
const htmlSanitization = this.checkHTMLSanitization(element);
if (htmlSanitization.detected) {
sanitization.detected = true;
sanitization.methods.push(...htmlSanitization.methods);
}
// 检查JavaScript净化
const jsSanitization = this.checkJavaScriptSanitization(element);
if (jsSanitization.detected) {
sanitization.detected = true;
sanitization.methods.push(...jsSanitization.methods);
}
// 检查CSS净化
const cssSanitization = this.checkCSSSanitization(element);
if (cssSanitization.detected) {
sanitization.detected = true;
sanitization.methods.push(...cssSanitization.methods);
}
// 评估净化效果
if (sanitization.detected) {
sanitization.effectiveness = this.evaluateSanitizationEffectiveness(
element,
sanitization.methods
);
}
return sanitization;
}
// 检查HTML净化
checkHTMLSanitization(element) {
const result = {
detected: false,
methods: []
};
const htmlSanitization = this.sanitizationMethods.html;
const content = element.innerHTML || element.textContent;
// 检查模式
for (const pattern of htmlSanitization.patterns) {
if (pattern.test(content)) {
result.detected = true;
result.methods.push(pattern.toString());
}
}
// 检查函数
for (const func of htmlSanitization.functions) {
if (content.includes(func)) {
result.detected = true;
result.methods.push(func);
}
}
return result;
}
// 检查JavaScript净化
checkJavaScriptSanitization(element) {
const result = {
detected: false,
methods: []
};
const jsSanitization = this.sanitizationMethods.javascript;
const content = element.innerHTML || element.textContent;
// 检查模式
for (const pattern of jsSanitization.patterns) {
if (pattern.test(content)) {
result.detected = true;
result.methods.push(pattern.toString());
}
}
// 检查函数
for (const func of jsSanitization.functions) {
if (content.includes(func)) {
result.detected = true;
result.methods.push(func);
}
}
return result;
}
// 检查CSS净化
checkCSSSanitization(element) {
const result = {
detected: false,
methods: []
};
const cssSanitization = this.sanitizationMethods.css;
const content = element.innerHTML || element.textContent;
// 检查模式
for (const pattern of cssSanitization.patterns) {
if (pattern.test(content)) {
result.detected = true;
result.methods.push(pattern.toString());
}
}
// 检查函数
for (const func of cssSanitization.functions) {
if (content.includes(func)) {
result.detected = true;
result.methods.push(func);
}
}
return result;
}
// 评估净化效果
evaluateSanitizationEffectiveness(element, methods) {
const effectiveness = {
level: 'unknown',
details: []
};
// 检查HTML转义
if (methods.some(m => m.includes('htmlspecialchars') || m.includes('htmlentities'))) {
effectiveness.level = 'high';
effectiveness.details.push('HTML special characters are properly escaped');
}
// 检查标签剥离
if (methods.some(m => m.includes('strip_tags'))) {
effectiveness.level = 'high';
effectiveness.details.push('HTML tags are stripped');
}
// 检查JavaScript转义
if (methods.some(m => m.includes('escape') || m.includes('encodeURI'))) {
effectiveness.level = 'high';
effectiveness.details.push('JavaScript special characters are properly escaped');
}
// 检查CSS转义
if (methods.some(m => m.includes('sanitizeCSS'))) {
effectiveness.level = 'high';
effectiveness.details.push('CSS special characters are properly escaped');
}
return effectiveness;
}
// 分析编码
analyzeEncoding(element) {
const encoding = {
charset: null,
contentEncoding: null,
responseEncoding: null
};
// 检测字符集
const charset = this.detectCharset(element);
if (charset) {
encoding.charset = charset;
}
// 检测内容编码
const contentEncoding = this.detectContentEncoding(element);
if (contentEncoding) {
encoding.contentEncoding = contentEncoding;
}
// 检测响应编码
const responseEncoding = this.detectResponseEncoding(element);
if (responseEncoding) {
encoding.responseEncoding = responseEncoding;
}
return encoding;
}
// 检测字符集
detectCharset(element) {
// 检查meta标签
const metaCharset = document.querySelector('meta[charset]');
if (metaCharset) {
return metaCharset.getAttribute('charset');
}
// 检查Content-Type头
const contentType = document.querySelector('meta[http-equiv="Content-Type"]');
if (contentType) {
const content = contentType.getAttribute('content');
const match = content.match(/charset=([^;]+)/i);
if (match) {
return match[1];
}
}
return null;
}
// 检测内容编码
detectContentEncoding(element) {
const content = element.innerHTML || element.textContent;
// 检查Base64编码
if (/^[A-Za-z0-9+/=]+$/.test(content)) {
return 'base64';
}
// 检查URL编码
if (/%[0-9A-Fa-f]{2}/.test(content)) {
return 'url';
}
// 检查HTML编码
if (/&[a-zA-Z]+;/.test(content)) {
return 'html';
}
// 检查JavaScript编码
if (/\\[xX][0-9A-Fa-f]{2}/.test(content)) {
return 'javascript';
}
return null;
}
// 检测响应编码
detectResponseEncoding(element) {
// 这里需要实现检测响应编码的逻辑
// 由于浏览器安全限制,可能需要通过其他方式获取
return null;
}
// 分析父上下文
analyzeParentContext(element) {
const parentContext = {
type: null,
sanitization: null,
encoding: null
};
if (element.parentElement) {
// 检测父元素上下文类型
parentContext.type = this.detectContextType(element.parentElement);
// 检测父元素净化方法
parentContext.sanitization = this.detectSanitization(element.parentElement);
// 检测父元素编码
parentContext.encoding = this.analyzeEncoding(element.parentElement);
}
return parentContext;
}
// 生成建议
generateRecommendations(analysis) {
const recommendations = [];
// 基于上下文类型的建议
for (const type of analysis.type) {
recommendations.push({
type: 'context',
description: `Use appropriate payload for ${type} context`,
priority: 'high'
});
}
// 基于位置的建议
if (analysis.location.attributeName) {
recommendations.push({
type: 'location',
description: `Consider attribute-specific payload for ${analysis.location.attributeName}`,
priority: 'medium'
});
}
// 基于净化方法的建议
if (analysis.sanitization.detected) {
recommendations.push({
type: 'sanitization',
description: `Bypass detected sanitization methods: ${analysis.sanitization.methods.join(', ')}`,
priority: 'high'
});
}
// 基于编码的建议
if (analysis.encoding.charset || analysis.encoding.contentEncoding) {
recommendations.push({
type: 'encoding',
description: `Consider encoding-specific payload for detected encodings`,
priority: 'medium'
});
}
// 基于父上下文的建议
if (analysis.parentContext.type) {
recommendations.push({
type: 'parent',
description: `Consider parent context restrictions: ${analysis.parentContext.type.join(', ')}`,
priority: 'medium'
});
}
return recommendations;
}
}
export const contextAnalyzer = new ContextAnalyzer();