VulnC.cs
23.8 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
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace VulnCrawler
{
public class VulnC : VulnAbstractCrawler
{
// protected override string RegexFuncPattern => $@"@@ \-(?<{OldStart}>\d+),(?<{OldLines}>\d+) \+(?<{NewStart}>\d+),(?<{NewLines}>\d+) @@ (?<{MethodName}>(static)?( const )? [\w]+ [\w]+\([\w \*\,\t\n]*[\)\,])";
protected override string RegexFuncPattern => $@"(?<{MethodName}>(unsigned|static)?( const )? [\w]+ [\w]+\(([\w \*\,\t\n])*[\)\,])";
protected override string Extension => ".c";
protected override string ReservedFileName => "CReserved.txt";
public override MatchCollection GetMatches(string patchCode) {
var regs = Regex.Matches(patchCode, RegexFuncPattern);
return regs;
}
public override string RemoveComment(string original) {
string txt = Regex.Replace(original, Environment.NewLine, "");
//StringBuilder sb = new StringBuilder();
//sb.Append("\"\"\"");
//sb.Append(@".*");
//sb.Append("\"\"\"");
string replace = txt;
//if (Regex.Match(txt, sb.ToString()).Success) {
// replace = Regex.Replace(txt, sb.ToString(), "");
//}
return replace;
}
public override IDictionary<string, IEnumerable<string>> ExtractGitCriticalMethodTable(string srcCode)
{
var table = new Dictionary<string, IEnumerable<string>>();
string prevMethodName = string.Empty;
StringBuilder builder = new StringBuilder();
var regex1 = new Regex("\n", RegexOptions.Compiled);
var regex2 = new Regex(@""".+""", RegexOptions.Compiled);
var regex3 = new Regex(@"^[+-]\s", RegexOptions.Compiled);
var regex4 = new Regex(@"^[+-]\s*(\*|\/\*|\*\/)", RegexOptions.Compiled);
// 라인으로 나누고 @@가 시작하는 곳까지 생략
var split = regex1.Split(srcCode).SkipWhile(s => !s.StartsWith("@@")).ToArray();
for(int i = 0; i < split.Length; i++)
{
string line = split[i].Trim();
// 문자열 제거
//line = Regex.Replace(line, @""".+""", "");
line = regex2.Replace(line, "");
var methodMatch = extractMethodLine.Match(line);
string methodName = methodMatch.Groups[MethodName].Value.Trim();
// 추가된, 제거된 라인인지 확인
if (regex3.IsMatch(line))
{
// 주석문인지 확인
if (regex4.IsMatch(line))
{
continue;
}
Console.WriteLine(line);
builder.AppendLine(line);
continue;
}
// 메서드 매칭이 성공했거나 마지막 문단일 경우
if (methodMatch.Success || i == split.Length - 1)
{
if (string.IsNullOrWhiteSpace(prevMethodName))
{
builder.Clear();
prevMethodName = methodName;
continue;
}
if (methodName.Contains("return"))
{
continue;
}
if (methodName.Contains("="))
{
continue;
}
if (!table.ContainsKey(prevMethodName))
{
table[prevMethodName] = new HashSet<string>();
}
var list = table[prevMethodName] as HashSet<string>;
foreach (var b in Regex.Split(builder.ToString(), "\n"))
{
// 각 수집된 라인 별로 크리티컬 변수 선정
foreach (var var in ExtractCriticalVariant(b))
{
if (string.IsNullOrWhiteSpace(var))
{
continue;
}
list.Add(var);
}
}
prevMethodName = methodName;
builder.Clear();
}
}
return table;
}
protected override string GetOriginalFunc(Stream oldStream, string methodName) {
StringBuilder oldBuilder = new StringBuilder();
string method = Regex.Escape(methodName);
using (var reader = new StreamReader(oldStream)) {
bool found = false;
bool found2 = false;
bool commentLine = false;
int bracketCount = -1;
string stringPattern = @"[""].*[""]";
string commentPattern = @"\/\*.+\*\/";
string commentPattern2 = @"\/\*";
string commentPattern3 = @"\*\/";
var regex1 = new Regex(commentPattern3, RegexOptions.Compiled);
var regex2 = new Regex(stringPattern, RegexOptions.Compiled);
var regex3 = new Regex(commentPattern2, RegexOptions.Compiled);
var regex4 = new Regex(commentPattern, RegexOptions.Compiled);
var regex5 = new Regex($"{method}", RegexOptions.Compiled);
var regex6 = new Regex($@"""[.]*({method})", RegexOptions.Compiled);
var regex7 = new Regex($@"{method}\s*" + @"\{", RegexOptions.Compiled);
while (!reader.EndOfStream) {
string line = reader.ReadLine();
// 메서드를 찾은 경우
if (found)
{
string trim = line.Trim();
// 범위 주석 진행되고 있으면 넘어감
if (trim.StartsWith("#"))
{
continue;
}
if (commentLine)
{
// 혹시 범위 주석이 끝났는지 체크
if (regex1.IsMatch(trim))
{
commentLine = false;
trim = regex1.Split(trim)[1];
}
else
{
continue;
}
}
// "" 문자열 제거
string removeString = regex2.Replace(trim, "");
// /* ~ 패턴
if (regex3.IsMatch(trim))
{
// /* ~ */ 패턴이 아닌 경우
if (!regex4.IsMatch(trim))
{
commentLine = true;
}
trim = Regex.Split(trim, "/*")[0];
}
// 비어있는 경우 넘어감
if (string.IsNullOrWhiteSpace(trim))
{
continue;
}
int openBracketCount = removeString.Count(c => c == '{');
int closeBracketCount = removeString.Count(c => c == '}');
int subtract = openBracketCount - closeBracketCount;
bracketCount += subtract;
// 메서드 시작 괄호 찾은 경우
if (found2)
{
oldBuilder.AppendLine(line);
// 괄호가 모두 닫혔으니 종료
if (bracketCount < 0)
{
break;
}
}
else // 메서드는 찾았으나 아직 시작 괄호를 못찾은 경우
{
oldBuilder.AppendLine(line);
if (openBracketCount > 0)
{
found2 = true;
}
else
{
//아직 { 괄호를 못찾았는데 );를 만났다면 메서드 선언 부분이니 넘어감
if (trim.EndsWith(");"))
{
found = false;
oldBuilder.Clear();
continue;
}
}
}
}
// 아직 메서드를 못찾은 경우
else
{
// 메서드 찾았는지 확인
if (regex5.Match(line).Success)
{
string trim = line.Trim();
// 주석으로 시작했다면 넘어감
if (trim.StartsWith("//"))
{
continue;
}
if (trim.StartsWith("/*"))
{
continue;
}
// 혹시 메서드가 문자열 사이에 있다면 넘어감..
if (regex6.Match(trim).Success)
{
continue;
}
// 만약 찾은 메서드 라인에서 중괄호 {가 시작된 경우
if (regex7.Match(trim).Success)
{
// 동시에 } 닫히기까지 한 경우 드물겠지만..
if (trim.EndsWith("}"))
{
oldBuilder.AppendLine(line);
break;
}
found2 = true;
}
// 메서드 찾음
found = true;
oldBuilder.AppendLine(line);
}
}
}
}
return oldBuilder.ToString();
}
protected override IList<Block> GetCriticalBlocks(string srcCode, IEnumerable<string> criticalList)
{
var blockList = new List<Block>();
StringBuilder builder = new StringBuilder();
var crList = criticalList as HashSet<string>;
if (crList == null)
{
return null;
}
var split = srcCode.Split('\n');
var mainQ = new Queue<string>();
var groupQ = new Queue<string>();
bool mainLine = true;
int crNum = 1;
int bracketCount = 1;
bool prevStartBlock = false;
int totalSoBracketCount = 0;
foreach (var line in split)
{
bool criticalBlock = false;
string trimLine = line.Trim();
if (string.IsNullOrWhiteSpace(trimLine))
{
continue;
}
if (mainLine)
{
bracketCount = 1;
if (trimLine.StartsWith("else"))
{
groupQ.Enqueue(line);
mainLine = false;
continue;
}
StringBuilder groupBuilder = new StringBuilder();
while(groupQ.Count > 0)
{
string s = groupQ.Dequeue();
if (!criticalBlock)
{
foreach (var item in ExtractCriticalVariant(s))
{
if (crList.Contains(item))
{
criticalBlock = true;
break;
}
}
}
groupBuilder.AppendLine(s);
}
if (!string.IsNullOrWhiteSpace(groupBuilder.ToString()))
{
blockList.Add(new Block { Code = groupBuilder.ToString(), HasCritical = criticalBlock, Num = crNum++});
}
if (Regex.IsMatch(trimLine, @"^(if|for|while|switch|do)\s*"))
{
/* syntax를 만났을 때 끝에 {가 없으면 */
if (!trimLine.EndsWith("{"))
{
int soBracketOpenCount = trimLine.Count(c => c == '(');
int soBracketCloseCount = trimLine.Count(c => c == ')');
totalSoBracketCount = (soBracketOpenCount - soBracketCloseCount);
/* if(s()
* && b)
* 이렇게 소괄호가 안맞고 밑 라인에서 이어서 작성하는 경우
*/
mainLine = false;
prevStartBlock = true;
}
else if (trimLine.EndsWith(";"))
{
mainLine = true;
}
else
{
mainLine = false;
bracketCount++;
}
groupQ.Enqueue(line);
continue;
}
mainQ.Enqueue(line);
}
else
{
/* 소괄호 수 세기 */
int soBracketOpenCount = trimLine.Count(c => c == '(');
int soBracketCloseCount = trimLine.Count(c => c == ')');
/* 중괄호 수 세기 */
int openBracketCount = trimLine.Count(c => c == '{');
int closeBracketCount = trimLine.Count(c => c == '}');
int subtract = openBracketCount - closeBracketCount;
bracketCount += subtract;
groupQ.Enqueue(line);
if (prevStartBlock)
{
totalSoBracketCount += (soBracketOpenCount - soBracketCloseCount);
prevStartBlock = false;
if(totalSoBracketCount > 0)
{
prevStartBlock = true;
continue;
}
else if (Regex.IsMatch(trimLine, @"^(if|for|while|switch|do)\s*"))
{
prevStartBlock = true;
continue;
}
else if(trimLine.EndsWith(";"))
{
bracketCount--;
}
}
if (bracketCount <= 1)
{
if (soBracketOpenCount > soBracketCloseCount)
{
continue;
}
if (!(trimLine.EndsWith("}") || trimLine.EndsWith(";")))
{
continue;
}
if (trimLine.Contains("else"))
{
bracketCount++;
prevStartBlock = true;
continue;
}
mainLine = true;
}
/* 메인 라인 블록 추가 */
StringBuilder mainBuilder = new StringBuilder();
while (mainQ.Count > 0)
{
string s = mainQ.Dequeue();
if (!criticalBlock)
{
/* 크리티칼 블록 선정 */
foreach (var item in ExtractCriticalVariant(s))
{
if (crList.Contains(item))
{
criticalBlock = true;
break;
}
}
}
mainBuilder.AppendLine(s);
}
string mains = mainBuilder.ToString();
if (!string.IsNullOrWhiteSpace(mains))
{
blockList.Add(new Block { Code = mains, HasCritical = criticalBlock, Num = crNum++ });
}
}
}
bool cb = false;
if (mainQ.Count > 0)
{
StringBuilder mainBuilder = new StringBuilder();
while (mainQ.Count > 0)
{
string s = mainQ.Dequeue();
if (!cb)
{
foreach (var item in ExtractCriticalVariant(s))
{
if (crList.Contains(item))
{
cb = true;
break;
}
}
}
mainBuilder.AppendLine(s);
}
if (mainBuilder.Length > 0)
{
blockList.Add(new Block { Code = mainBuilder.ToString(), HasCritical = cb, Num = crNum++ });
}
}
else
{
StringBuilder groupBuilder = new StringBuilder();
while (groupQ.Count > 0)
{
string s = groupQ.Dequeue();
if (!cb)
{
foreach (var item in ExtractCriticalVariant(s))
{
if (crList.Contains(item))
{
cb = true;
break;
}
}
}
groupBuilder.AppendLine(s);
}
if (groupBuilder.Length > 0)
{
blockList.Add(new Block { Code = groupBuilder.ToString(), HasCritical = cb, Num = crNum++ });
}
}
return blockList;
}
public override string Abstract(string blockCode, IDictionary<string, string> dict, IDictionary<string, string> methodDict)
{
var split = blockCode.Split('\n');
var varName = "VAL";
var methodName = "FUNC";
var d = new Dictionary<string, string>();
int varIdx = dict.Count();
int methodIdx = methodDict.Count();
var dict2 = new Dictionary<string, string>();
var methodDict2 = new Dictionary<string, string>();
int varIdx2 = 0;
int methodIdx2 = 0;
//var regex1 = new Regex(@"\s*$|^\s*", RegexOptions.Compiled);
var regex1 = new Regex(@"\s*$", RegexOptions.Compiled);
var removes = Regex.Split(blockCode, Environment.NewLine, RegexOptions.Multiline);
StringBuilder builder = new StringBuilder();
Console.ForegroundColor = ConsoleColor.DarkYellow;
foreach (var item in removes)
{
if (string.IsNullOrWhiteSpace(item))
{
continue;
}
string rm = regex1.Replace(item, "");
builder.Append(rm);
}
Console.WriteLine(builder.ToString());
Console.ResetColor();
string line = builder.ToString();
var varList = ExtractMethodVariantList(line, skipDefine: false);
if (varList == null)
{
return string.Empty;
}
foreach (var var in varList.Vars)
{
if (!dict.ContainsKey(var))
{
dict[var] = varName + varIdx++;
}
if (!dict2.ContainsKey(var))
{
dict2[var] = varName + varIdx2++;
}
}
foreach (var m in varList.Methods)
{
if (!methodDict.ContainsKey(m))
{
methodDict[m] = methodName + methodIdx++;
}
if (!methodDict2.ContainsKey(m))
{
methodDict2[m] = methodName + methodIdx2++;
}
}
//var sortVarDict = dict.OrderByDescending(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
//var sortMethodDict = methodDict.OrderByDescending(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
var sortVarDict2 = dict2.OrderByDescending(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
var sortMethodDict2 = methodDict2.OrderByDescending(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
string temp = blockCode;
foreach (var pair in sortVarDict2)
{
string pk = pair.Key;
string pv = pair.Value;
if (pk.Contains("->"))
{
var connects = Regex.Split(pk, "->");
var connectList = new List<string>();
string result = string.Empty;
string s = string.Empty;
foreach (var c in connects)
{
if (s == string.Empty)
{
s = c;
continue;
}
if (sortVarDict2.ContainsKey(s))
{
if (result == string.Empty)
{
result = sortVarDict2[s];
}
else
{
result = string.Join("->", result, sortVarDict2[s]);
}
}
s = string.Join("->", s, c);
}
if (result != string.Empty)
{
result = string.Join("->", result, pv);
pv = result;
}
}
temp = Regex.Replace(temp, $@"\b{pk}\b", pv);
}
foreach (var pair in sortMethodDict2)
{
temp = Regex.Replace(temp, $@"\b{pair.Key}\b", pair.Value);
}
temp = Regex.Replace(temp, @"\s", "", RegexOptions.Multiline);
temp = Regex.Replace(temp, @"{|}|;|\)|\(", "");
temp = temp.ToUpper();
return temp;
}
}
}