VulnAbstractCrawler.cs 15 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
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
    {
        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() {
            Repository?.Dispose();
        }
        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("로딩중");
            Repository = new Repository(path);
            Console.WriteLine("로딩 완료");
            Commits = SearchCommits();
        }
        /// <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 Extension { get; }
        public virtual IEnumerable<PatchEntryChanges> GetPatchEntryChanges(Patch patch) {
            return patch.Where(e => e.Path.EndsWith(Extension)).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); 
        
        /// <summary>
        /// 성능 개선을 위한
        /// 코드 라인 위치 기반 취약 원본 함수 추출 테스트용 함수 곧 삭제 예정
        /// </summary>
        public string GetOriginalFuncTest(Stream oldStream, string methodName, int start)
        {
            StringBuilder oldBuilder = new StringBuilder();
            
            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 = @"\*\/";
                int readCount = 0;
                Queue<string> tempQ = new Queue<string>();
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();


                    if (readCount++ < start)
                    {
                        tempQ.Enqueue(line);
                        continue;
                    }
                    Stack<string> tempStack = new Stack<string>();
                    while (tempQ.Count > 0)
                    {
                        string s = tempQ.Dequeue();
                        tempStack.Push(s);
                        string method = Regex.Escape(methodName);
                        if (Regex.Match(s, $"{method}").Success)
                        {

                            break;
                        }
                    }

                    while (tempStack.Count > 0)
                    {
                        string s = tempStack.Pop();
                        string trim = s.Trim();

                        if (commentLine)
                        {
                            if (Regex.IsMatch(trim, commentPattern3))
                            {
                                commentLine = false;
                                trim = Regex.Split(trim, commentPattern3)[1];
                            }
                            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)
                        {
                            // 괄호가 모두 닫혔으니 종료
                            if (bracketCount < 0)
                            {
                                Console.WriteLine("괄호끝");
                                break;
                            }
                          //  oldBuilder.AppendLine(line);
                        }
                        else
                        {
                            if (openBracketCount > 0)
                            {
                                found2 = true;
                            }

                        }
                        oldBuilder.AppendLine(s);
                    }


                }

            }
            Console.WriteLine("찾음");
            Console.WriteLine(oldBuilder.ToString());
            Console.ReadLine();

            return oldBuilder.ToString();
        }


        public abstract IDictionary<string, IEnumerable<string>> ExtractGitCriticalMethodTable(string srcCode);
        /// <summary>
        /// 실제 프로세스
        /// </summary>
        /// <param name="oldStream"></param>
        /// <param name="methodName"></param>
        /// <returns></returns>
        public virtual (string originalFunc, string hash) Process(Stream oldStream, string methodName, int start) {
            // 패치 전 원본 함수 구하고
            string func = GetOriginalFunc(oldStream, methodName);
            // 주석 제거하고
            //func = RemoveComment(func);
            // 해쉬하고
            string md5 = MD5HashFunc(func);
            // 튜플로 반환
            return (func, md5);
        }
        /// <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("출력중");
            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 match.Value;
            }
            return string.Empty;
        }

        /// <summary>
        /// 크리티컬 변수 목록 추출
        /// </summary>
        /// <param name="line">현재 코드줄</param>
        /// <returns></returns>
        public IEnumerable<string> ExtractCriticalVariant(string line)
        {
            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 = @"^*?[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;
                                }
                                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>
        protected 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();
        }
    }
}