VulnAbstractCrawler.cs 22.2 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
using LibGit2Sharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VulnCrawler
{

    // 추상 클래스
    public abstract class VulnAbstractCrawler
    {
        public class Block
        {
            public int Num { get; set; }
            public bool HasCritical { get; set; }
            public string Code { get; set; }
            public string Hash { get; set; }
            public string AbsCode { get; set; }
            public IEnumerable<string> CriticalList { get; set; }

        }

        public class UserBlock
        {
            public int Len { get; set; }
            public string FuncName { get; set; }
            public string Hash { get; set; }
            public string Path { get; set; }

            public override bool Equals(object obj)
            {
                var block = obj as UserBlock;
                return block != null &&
                       Hash == block.Hash;
            }

            public override int GetHashCode()
            {
                var hashCode = -481433985;
                hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Hash);
                return hashCode;
            }
        }
        public string PushUrl { get; set; }
        protected Regex extractMethodLine;
        protected HashSet<string> ReservedList { get; }
        protected abstract string ReservedFileName { get; }
        // = { "if", "return", "break", "while", "typedef" };
        /// <summary>
        /// 생성자
        /// 경로를 입력받아서(path)
        /// 레파지토리를 초기화하고
        /// 커밋 목록을 검색함
        /// </summary>
        /// <param name="path"></param>
        public VulnAbstractCrawler()
        {
            extractMethodLine = new Regex(RegexFuncPattern);
            ReservedList = new HashSet<string>();
            LoadReservedList();
        }
        // 소멸자
        ~VulnAbstractCrawler() {
            try
            {
                Repository?.Dispose();
            }
            catch { }
        }

        private void LoadReservedList()
        {
            try
            {
                var lines = File.ReadLines(ReservedFileName, Encoding.Default);
                foreach (var item in lines)
                { 
                    if (string.IsNullOrWhiteSpace(item))
                    {
                        continue;
                    }
                    ReservedList.Add(item);  
                }
            }
            catch(FileNotFoundException)
            {
                Console.WriteLine($"{this.GetType().ToString()} 예약어 파일 목록이 없습니다. 파일 이름 : {ReservedFileName}");
            }
        }
        protected virtual Regex MethodExtractor => new Regex(RegexFuncPattern);
        #region 메서드 패턴 정규식 그룹
        // 정규식 그룹화
        // @@ -oldStart,oldLines +newStart,newLines @@ MethodName():
        public static string OldStart => "oldStart";
        public static string OldLines => "oldLines";
        public static string NewStart => "newStart";
        public static string NewLines => "newLines";
        public static string MethodName => "methodName";
        #endregion

        public void Init(string path) {
            Console.WriteLine("로딩중");
            Console.WriteLine(path);
            Repository = new Repository(path);
            PushUrl = Repository.Network.Remotes.FirstOrDefault().PushUrl;

            if (PushUrl.EndsWith(".git"))
            {
                PushUrl = PushUrl.Replace(".git", "");

            }

            Console.WriteLine("로딩 완료");
            Commits = SearchCommits();
            Console.WriteLine($"Commits Count: {Commits.Count()}");
        }
        /// <summary>
        /// 레파지토리
        /// </summary>
        public Repository Repository { get; private set; }

        /// <summary>
        /// 커밋 목록
        /// </summary>
        public IEnumerable<Commit> Commits { get; private set; }
        /// <summary>
        /// 커밋에서 검색할 정규식 문자열
        /// </summary>
        public string SearchCommitPattern => @"CVE[ -](\d{4})[ -](\d{4,})";
        /// <summary>
        /// 패치 코드에서 함수 찾을 정규식 패턴 문자열
        /// </summary>
        protected abstract string RegexFuncPattern { get; }
        protected abstract string UserRegexFuncPattern { get; }
        protected abstract string Extension { get; }
        public virtual IEnumerable<PatchEntryChanges> GetPatchEntryChanges(Patch patch) {
            return patch.Where(e => e.Path.EndsWith(Extension) && e.Status == ChangeKind.Modified).ToList();
        }
        /// <summary>
        /// 정규식을 이용하여 @@ -\d,\d +\d,\d @@ MethodName(): 이런 패턴을 찾고
        /// 그룹화 하여 반환함 (OldStart, OldLines, NewStart, NewLines, MethodName
        /// </summary>
        /// <param name="patchCode">찾을 코드</param>
        /// <returns>정규식 그룹 컬렉션</returns>
        public abstract MatchCollection GetMatches(string patchCode);
        /// <summary>
        /// 파일스트림으로 부터 원본 함수 구하는 함수
        /// </summary>
        /// <param name="oldStream">파일 스트림</param>
        /// <param name="methodName">찾을 메서드 이름</param>
        /// <returns>함수 문자열</returns>
        protected abstract string GetOriginalFunc(Stream oldStream, string methodName);

        public abstract IDictionary<int, IEnumerable<UserBlock>> CrawlUserCode(StreamReader reader);

        protected abstract IList<Block> GetCriticalBlocks(string srcCode, IEnumerable<string> criticalList);

        public abstract IDictionary<string, IEnumerable<string>> ExtractGitCriticalMethodTable(string srcCode);

        public abstract IDictionary<string, string> CrawlCode(StreamReader reader);

        public abstract string Abstract(string blockCode, IDictionary<string, string> dict, IDictionary<string, string> methodDict);
        /// <summary>
        /// 패치 전 코드 파일과 크리티컬 메서드 테이블로 부터 크리티컬 블록 추출
        /// </summary>
        /// <param name="oldBlob">패치 전 파일 Blob</param>
        /// <param name="table">크리티컬 메서드 테이블(Key: 메서드 이름, Value: 변수 리스트)</param>
        /// <returns></returns>
        public virtual IEnumerable<(string methodName, string oriFunc, IList<Block> blocks)> Process(Blob oldBlob, IDictionary<string, IEnumerable<string>> table) {

            // 패치 전 원본 파일 스트림
            Stream oldStream = oldBlob.GetContentStream();
            using (var reader = new StreamReader(oldStream))
            {
                var dict = CrawlCode(reader);

                foreach (var item in table)
                {
                    var methodTable = new Dictionary<string, string>();
                    var varTable = new Dictionary<string, string>();
                    // 메서드 이름
                    string methodName = item.Key;

                    // 패치 전 원본 함수 구하고
                    string func = string.Empty;


                    foreach (var pair in dict)
                    {
                        if (pair.Key.Contains(methodName))
                        {
                            func = pair.Value;
                            break;
                        }
                    }




                    // 크리티컬 블록 추출
                    var blocks = new List<Block>();
                    yield return (methodName, func, blocks);
                  

                }
            }
        }
        /// <summary>
        /// 주석 제거 함수
        /// </summary>
        /// <param name="original">제거할 문자열</param>
        /// <returns>결과 문자열</returns>
        public abstract string RemoveComment(string original);

        /// <summary>
        /// 커밋 검색 함수(정규식 사용)
        /// 정규식은 SearchKeyword 사용함
        /// </summary>
        /// <returns>커밋 목록</returns>
        public virtual IEnumerable<Commit> SearchCommits() {
            // where => 조건에 맞는 것을 찾음(CVE-20\d\d-\d{4}로 시작하는 커밋만 골라냄)
            Console.WriteLine(Repository.Commits.Count());
            var commits = Repository.Commits
                                    .Where(c => Regex.Match(c.Message, SearchCommitPattern, RegexOptions.IgnoreCase).Success)
                                    .ToList();

            return commits;
        }

        /// <summary>
        /// 커밋 메시지로부터 CVE 코드 추출
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string GetCVE(string msg) {
            var match = Regex.Match(msg, SearchCommitPattern, RegexOptions.IgnoreCase);

            if (match.Success) {
                return $"CVE-{match.Groups[1].Value}-{match.Groups[2].Value}";
            }
            return string.Empty;
        }
        

        public MethodVarList ExtractMethodVariantList(string line, bool skipDefine=true)
        {
            line = line.Trim();
            if (string.IsNullOrWhiteSpace(line))
            {
                return null;
            }
            if (line.StartsWith("//"))
            {
                return null;
            }
            var methodVarList = new MethodVarList() { Methods = new List<string>(), Vars = new List<string>() };
            string declarePattern = @"(?<Declare>[a-zA-Z0-9_\.]+)\s+[a-zA-Z0-9_\.]+\s*(=|;|,)";
            // 메서드 정규식 패턴
            string methodPattern = @"([a-zA-Z0-9_\.]+)\s*\(";
            // 변수 정규식 패턴
            string fieldPattern = @"\*?(?<Field>([a-zA-Z0-9_\.]|\-\>)+)";
            string fieldArrayPattern = @"(?<ArrayName>[a-zA-Z0-9_\.]+)\[.+\]";
            string invalidPattern = @"^[\d\.]+";

            string commentPattern = @"[""].*[""]";

            string commentPattern2 = @"\/\/.*";
            string commentPattern3 = @"\/\*.+\*\/";

            line = Regex.Replace(line, commentPattern, "");
            line = Regex.Replace(line, commentPattern2, "");
            line = Regex.Replace(line, commentPattern3, "");
            // 메서드 목록
            var methodSets = new HashSet<string>();

            // 선언 타입명 추출
            var declareMatch = Regex.Match(line, Regex.Escape(declarePattern));
            string declareName = string.Empty;
            if (declareMatch.Success)
            {
                declareName = declareMatch.Groups["Declare"]?.Value ?? string.Empty;

            }
            var methods = Regex.Matches(line, methodPattern);
            // 현재 코드 라인에서 메서드 목록 추가
            foreach (var met in methods)
            {
                var method = met as Match;
                if (method.Success)
                {
                    if (ReservedList.Contains(method.Groups[1].Value))
                    {
                        continue;
                    }
                    methodSets.Add(method.Groups[1].Value);
                }
            }
            //  Console.WriteLine("----");
            var arrayNames = Regex.Matches(line, fieldArrayPattern)
                            .Cast<Match>()
                            .Where(m => {
                                if (m.Value.Equals(declareName))
                                {
                                    return false;
                                }

                                /* 제일 앞자리가 숫자로 시작하면 넘어감 */
                                if (Regex.IsMatch(m.Value, invalidPattern))
                                {
                                    return false;
                                }

                                /* 전 단계에서 구한 메서드 목록에 있으면 넘어감 */
                                if (methodSets.Contains(m.Value))
                                {
                                    return false;
                                }
                                /* 예약어 목록에 있으면 넘어감 */
                                if (ReservedList.Contains(m.Value))
                                {
                                    return false;
                                }

                                /* 알파벳이 하나도 없으면 넘어감 */
                                if (!m.Value.Any(c => char.IsLetter(c)))
                                {
                                    return false;
                                }

                                ///* 대문자로 구성된 변수면 넘어감 */
                                //if (skipDefine && m.Value.All(c => char.IsUpper(c) || !char.IsLetter(c)))
                                //{
                                //    return false;
                                //}

                                return true;
                            })
                            .Distinct(new MatchComparer());

            var arrays = arrayNames.Select(m => m.Groups["ArrayName"].Value);

            var vars = Regex.Matches(line, fieldPattern)
                            .Cast<Match>()
                            .Where(m => {
                                if (m.Value.Equals(declareName))
                                {
                                    return false;
                                }

                                /* 제일 앞자리가 숫자로 시작하면 넘어감 */
                                if (Regex.IsMatch(m.Value, invalidPattern))
                                {
                                    return false;
                                }
                                
                                /* 전 단계에서 구한 메서드 목록에 있으면 넘어감 */
                                if (methodSets.Contains(m.Value))
                                {
                                    return false;
                                }
                                /* 예약어 목록에 있으면 넘어감 */
                                if (ReservedList.Contains(m.Value))
                                {
                                    return false;
                                }
                                if (m.Value.StartsWith("-"))
                                {
                                    return false;
                                }
                                /* 알파벳이 하나도 없으면 넘어감 */
                                if(!m.Value.Any(c => char.IsLetter(c)))
                                {
                                    return false;
                                }

                                ///* 대문자로 구성된 변수면 넘어감 */
                                //if (skipDefine && m.Value.All(c => char.IsUpper(c) || !char.IsLetter(c)))
                                //{
                                //    return false;
                                //}

                                return true;
                            })
                            .Distinct(new MatchComparer());

     
            foreach (var x in vars)
            {
                if (x.Success)
                {
                    var field = x.Groups["Field"].Value;

                    /* a->b 포인터 변수 나눠서 추가 */
                    if (field.Contains("->"))
                    {
                        var connects = Regex.Split(field, "->");
                        var connectList = new List<string>();

                        string s = string.Empty;
                        foreach (var c in connects)
                        {
                            if (s == string.Empty)
                            {
                                s = c;
                            }
                            else
                            {
                                s = string.Join("->", s, c);
                            }
                            connectList.Add(s);
                        }
                        foreach (var c in connectList)
                        {
                            if (c == connects[connects.Length-1])
                            {
                                continue;
                            }
                            if (methodVarList.Vars.Contains(c))
                            {
                                continue;
                            }
                            methodVarList.Vars.Add(c);
                        }
                        continue;
                    }
                    methodVarList.Vars.Add(field);
                }
            }
            foreach (var x in arrays)
            {
                 methodVarList.Vars.Add(x);
            }
            foreach (var m in methodSets)
            {
                methodVarList.Methods.Add(m);
            }
            return methodVarList;
        }

        /// <summary>
        /// 크리티컬 변수 목록 추출
        /// </summary>
        /// <param name="line">현재 코드줄</param>
        /// <returns></returns>
        public IEnumerable<string> ExtractCriticalVariant(string line, bool skipDefine=true)
        {
            line = line.Trim();
            if (string.IsNullOrWhiteSpace(line))
            {
                yield break;
            }
            if (line.StartsWith("//"))
            {
                yield break;
            }
            string declarePattern = @"(?<Declare>[a-zA-Z0-9_\.]+) [a-zA-Z0-9_\.]+ =";
            // 메서드 정규식 패턴
            string methodPattern = @"([a-zA-Z0-9_\.]+)\s*\(";
            // 변수 정규식 패턴
            string fieldPattern = @"\*?(?<Field>([a-zA-Z0-9_\.]|\-\>)+)";
            string invalidPattern = @"^[\d\.]+";

            string commentPattern = @"[""].*[""]";

            string commentPattern2 = @"\/\/.*";
            string commentPattern3 = @"\/\*.+\*\/";

            line = Regex.Replace(line, commentPattern, "");
            line = Regex.Replace(line, commentPattern2, "");
            line = Regex.Replace(line, commentPattern3, "");
            // 메서드 목록
            var methodSets = new HashSet<string>();

            // 선언 타입명 추출
            var declareMatch = Regex.Match(line, declarePattern);
            string declareName = string.Empty;
            if (declareMatch.Success)
            {
                declareName = declareMatch.Groups["Declare"]?.Value ?? string.Empty;

            }
            //Console.WriteLine($"선언 : {declareName}");


            var methods = Regex.Matches(line, methodPattern);
            // 현재 코드 라인에서 메서드 목록 추가
            foreach (var met in methods)
            {
                var method = met as Match;
                if (method.Success)
                {
                  //  Console.WriteLine(method.Groups[1].Value);
                    methodSets.Add(method.Groups[1].Value); // aaaa
                }
            }
          //  Console.WriteLine("----");
            var vars = Regex.Matches(line, fieldPattern)
                            .Cast<Match>()
                            .Where(m => {
                                if (m.Value.Equals(declareName))
                                {
                                    return false;
                                }
                                /* 제일 앞자리가 숫자로 시작하면 넘어감 */
                                if (Regex.IsMatch(m.Value, invalidPattern))
                                {
                                    return false;
                                }
                                /* 전 단계에서 구한 메서드 목록에 있으면 넘어감 */
                                if (methodSets.Contains(m.Value))
                                {
                                    return false;
                                }
                                /* 예약어 목록에 있으면 넘어감 */
                                if (ReservedList.Contains(m.Value))
                                {
                                    return false;
                                }
                                /* 알파벳이 하나도 없으면 넘어감 */
                                if(!m.Value.Any(c => char.IsLetter(c)))
                                {
                                    return false;
                                }
                                /* 대문자로 구성된 변수면 넘어감 */
                                if (skipDefine && m.Value.All(c => char.IsUpper(c) || !char.IsLetter(c)))
                                {
                                    return false;
                                }
                                return true;
                            })
                            .Distinct(new MatchComparer());

            foreach (var x in vars)
            {
                var field = x as Match;
                if (field.Success)
                {
                    yield return field.Value;
                }
            }
        }

        /// <summary>
        /// MD5 함수
        /// </summary>
        /// <param name="str">INPUT 문자열</param>
        /// <returns>결과 문자열</returns>
        public static string MD5HashFunc(string str) {
            StringBuilder MD5Str = new StringBuilder();
            byte[] byteArr = Encoding.ASCII.GetBytes(str);
            byte[] resultArr = (new MD5CryptoServiceProvider()).ComputeHash(byteArr);
            for (int cnti = 0; cnti < resultArr.Length; cnti++) {
                MD5Str.Append(resultArr[cnti].ToString("X2"));
            }
            return MD5Str.ToString();
        }

    }

    class MatchComparer : IEqualityComparer<Match>
    {
        public bool Equals(Match x, Match y)
        {
            return x.Value.Equals(y.Value);
        }

        public int GetHashCode(Match obj)
        {
            return obj.Value.GetHashCode();
        }
    }

    public class MethodVarList
    {
        public IList<string> Vars { get; set; }
        public IList<string> Methods { get; set; }
    }
}