VulnC.cs 17.5 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
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 split = Regex.Split(srcCode, "\n").SkipWhile(s => !s.StartsWith("@@")).ToArray();
            for(int i = 0; i < split.Length; i++)
            {
                string line = split[i].Trim();
                // 문자열 제거
                line = Regex.Replace(line, @""".+""", "");

                var methodMatch = extractMethodLine.Match(line);
                string methodName = methodMatch.Groups[MethodName].Value.Trim();
                // 추가된, 제거된 라인인지 확인
                if (Regex.IsMatch(line, @"^[+-]\s"))
                {
                    // 주석문인지 확인
                    if (Regex.IsMatch(line, @"^[+-]\s*(\*|\/\*|\*\/)"))
                    {
                        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 = @"\*\/";
                while (!reader.EndOfStream) {
                    string line = reader.ReadLine();
                    // 메서드를 찾은 경우
                    if (found)
                    {
                        string trim = line.Trim();
                        // 범위 주석 진행되고 있으면 넘어감
                        if (commentLine)
                        {
                            // 혹시 범위 주석이 끝났는지 체크
                            if (Regex.IsMatch(trim, commentPattern3))
                            {
                                commentLine = false;
                                trim = Regex.Split(trim, commentPattern3)[1];
                            }
                            else
                            {
                                continue;
                            }
                        }
                        // "" 문자열 제거
                        string removeString = Regex.Replace(trim, stringPattern, "");
                        // /* ~ 패턴
                        if (Regex.IsMatch(trim, commentPattern2))
                        {
                            
                            // /* ~ */ 패턴이 아닌 경우
                            if (!Regex.IsMatch(trim, commentPattern))
                            {
                                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 (Regex.Match(line, $"{method}").Success)
                        {
                            string trim = line.Trim();
                            // 주석으로 시작했다면 넘어감
                            if (trim.StartsWith("//"))
                            {
                                continue;
                            }

                            if (trim.StartsWith("/*"))
                            {
                                continue;
                            }
                            
                            // 혹시 메서드가 문자열 사이에 있다면 넘어감..
                            if (Regex.Match(trim, $@"""[.]*({method})").Success)
                            {
                                continue;
                            }
                            // 만약 찾은 메서드 라인에서 중괄호 {가 시작된 경우
                            if (Regex.Match(trim, $@"{method}\s*" + @"\{").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)
        {
           // srcCode = Regex.Replace(srcCode, @"if.+\n\{", @"if.+\{", RegexOptions.Multiline);

            var split = srcCode.Split('\n');
            var blockList = new List<Block>();
            StringBuilder builder = new StringBuilder();
            var crList = criticalList as HashSet<string>;
            if (crList == null)
            {
                return null;
            }

            var mainQ = new Queue<string>();
            var groupQ = new Queue<string>();
            bool mainLine = true;
            int crNum = 1;
            int bracketCount = 1;
            bool prevStartBlock = false;
            foreach (var line in split)
            {
                bool criticalBlock = false;
                string trimLine = line.Trim();
                if (mainLine)
                {
                    if (trimLine.EndsWith("&&") || trimLine.EndsWith("||"))
                    {
                        mainQ.Enqueue(line);
                        continue;
                    }

                    if (trimLine.StartsWith("&&") || trimLine.StartsWith("||"))
                    {
                        groupQ.Enqueue(line);
                        continue;
                    }



                    bracketCount = 1;
                    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 (groupBuilder.Length > 0)
                    {
                        blockList.Add(new Block { Code = groupBuilder.ToString(), HasCritical = criticalBlock, Num = crNum++});
                    }
                    if (Regex.IsMatch(trimLine, @"(if|for|while|switch|do)\s*"))
                    {
                        if (!trimLine.EndsWith("{"))
                        {
                            mainLine = false;
                            prevStartBlock = true;
                            
                        }
                        else if (trimLine.EndsWith(";"))
                        {
                            mainLine = true;
                        }
                        else
                        {
                            mainLine = false;
                            bracketCount++;
                        }
                        
                        groupQ.Enqueue(line);
                        

                        continue;
                    }
                    mainQ.Enqueue(line);
                }
                else
                {
                    

                    /* 중괄호 수 세기 */
                    int openBracketCount = trimLine.Count(c => c == '{');
                    int closeBracketCount = trimLine.Count(c => c == '}');
                    int subtract = openBracketCount - closeBracketCount;
                    bracketCount += subtract;


                    if (trimLine.EndsWith("&&") || trimLine.EndsWith("||"))
                    {
                        groupQ.Enqueue(line);
                        continue;
                    }

                    //if (trimLine.StartsWith("&&") || trimLine.StartsWith("||"))
                    //{
                    //    mainQ.Enqueue(line);
                    //    continue;

                    //}
                    groupQ.Enqueue(line);
                    if (prevStartBlock)
                    {
                        prevStartBlock = false;
                        if (Regex.IsMatch(trimLine, @"(if|for|while|switch|do)\s*\("))
                        {
                            prevStartBlock = true;
                            continue;

                        }
                        else if(trimLine.EndsWith(";"))
                        {
                            bracketCount--;
                        }
                    }

                    if (bracketCount <= 1)
                    {
                        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);
                    }

                    if (mainBuilder.Length > 0)
                    {
                        blockList.Add(new Block { Code = mainBuilder.ToString(), 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;
        }
    }
}