Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

windbg - "*** WARNING: Unable to verify checksum for" 경고 없애는 방법

.NET EXE/DLL을 windbg에서 디버깅하는 경우 pdb 정보가 요구되는 명령어의 출력에 꼭 다음과 같은 경고가 나옵니다.

0:000> !clrstack
OS Thread Id: 0x2bc0 (0)
        Child SP               IP Call Site
000000a3674fed20 00007ffec2dd04c1 *** WARNING: Unable to verify checksum for ConsoleApp1.exe
ConsoleApp1.Program.Main(System.String[]) [E:\ConsoleApp1\Program.cs @ 15]
000000a3674ff0a0 00007fff223c6793 [GCFrame: 000000a3674ff0a0] 

물론 symbol 로딩 명령어에도 나옵니다.

0:000> .reload -f
.*** WARNING: Unable to verify checksum for ConsoleApp1.exe
..........................
Loading unloaded module list

이게 나오는 원인은 PE header의 checksum 데이터가 없기 때문입니다. 이는 windbg에서 !dh 명령어로 확인할 수 있습니다.

0:000> !dh ConsoleApp1

File Type: EXECUTABLE IMAGE
FILE HEADER VALUES
     14C machine (i386)
       3 number of sections
59DF6494 time date stamp Thu Oct 12 05:48:20 2017

       0 file pointer to symbol table
       0 number of symbols
      F0 size of optional header
      22 characteristics
            Executable
            App can handle >2gb addresses

OPTIONAL HEADER VALUES
     20B magic #
   48.00 linker version
     C00 size of code
     800 size of initialized data
       0 size of uninitialized data
    2B36 address of entry point
    2000 base of code
         ----- new -----
0000000000400000 image base
    2000 section alignment
     200 file alignment
       3 subsystem (Windows CUI)
    4.00 operating system version
    0.00 image version
    6.00 subsystem version
    8000 size of image
     200 size of headers
       0 checksum
0000000000100000 size of stack reserve
0000000000001000 size of stack commit
0000000000100000 size of heap reserve
...[이하 생략]...

보는 바와 같이 "0 checksum"으로 값이 0입니다.

.NET의 경우 checksum 데이터를 Debug/Release 버전에 상관없이 생성하지 않으므로 저 경고는 언제나 발생할 수밖에 없습니다. 대신 위안이 되는 것은, 경고 외에는 windbg의 닷넷 어셈블리 분석에 아무런 영향도 미치지 않기 때문에 무시하면 그만이라는 점입니다. (심지어 !clrstack 명령어는 두 번째 실행부터는 해당 경고를 출력하지 않습니다. 정말... 이 경고는 아주 경미하게 거슬리는 정도입니다.)




혹시나 결벽증이 있는 분을 위해... 더 말씀드리면, checksum 데이터가 다행히 계산 방법이 공개되어 있어 원한다면 설정해 버리면 됩니다. 이에 대해서는 다음의 글에 자세히 나옵니다.

An Analysis of the Windows PE Checksum Algorithm
; https://www.codeproject.com/Articles/19326/An-Analysis-of-the-Windows-PE-Checksum-Algorithm

게다가 위의 글에 보면 PEChecksum.exe라는 도구를 공개해 직접 계산된 값을 설정할 수 있습니다. 그렇다면 C#으로도 한번 만들어 볼까요? ^^ 다행히 코드도 다음의 링크에서 쉽게 구했습니다.

portable-executable-library/pe_lib/pe_checksum.cpp 
; https://github.com/mrexodia/portable-executable-library/blob/master/pe_lib/pe_checksum.cpp#L43

이와 함께 지난번에 다뤘던 Workshell.PE 라이브러리를 NuGet으로부터 받아,

Install-Package Workshell.PE -Version 1.7.0

다음과 같이 간단하게 만들어 줄 수 있습니다.

// https://github.com/stjeong/SetPEChecksum

using System;
using System.IO;
using Workshell.PE;

namespace SetPEChecksum
{
    class Program
    {
        // https://github.com/mrexodia/portable-executable-library/blob/master/pe_lib/pe_checksum.cpp#L43
        static int Main(string[] args)
        {
            if (args.Length != 1 && args.Length != 2)
            {
                Console.WriteLine("[options] file_path");
                Console.WriteLine("/s - calc & set checksum");
                return 1;
            }

            bool setNewChecksum = false;
            string filePath = null;

            if (args[0] == "/s" || args[0] == "-s")
            {
                setNewChecksum = true;
                filePath = args[1];
            }
            else
            {
                filePath = args[0];
            }

            uint currentCheckSum = 0;
            uint newCheckSum = 0;
            uint checkSumPos = 0;

            using (Workshell.PE.ExecutableImage pe = Workshell.PE.ExecutableImage.FromFile(filePath))
            {
                currentCheckSum = pe.NTHeaders.OptionalHeader.CheckSum;
                Console.WriteLine($"Current Checksum: {currentCheckSum}(0x{currentCheckSum.ToString("x")})");

                newCheckSum = CalcChecksum(pe, out checkSumPos);
                Console.WriteLine($"New Checksum: {newCheckSum}(0x{newCheckSum.ToString("x")})");
            }

            if (setNewChecksum == true && (currentCheckSum != newCheckSum))
            {
                byte[] contents = File.ReadAllBytes(filePath);
                byte[] newCheckSumBuffer = BitConverter.GetBytes(newCheckSum);
                Array.Copy(newCheckSumBuffer, 0, contents, checkSumPos, 4);

                try
                {
                    File.WriteAllBytes(filePath, contents);
                }
                catch (System.IO.IOException)
                {
                    string newFilePath = filePath + ".new";
                    Console.WriteLine($"New file({newFilePath}) created because it is being used by another process.");
                    File.WriteAllBytes(newFilePath, contents);
                }
            }

            return 0;
        }

        private static uint CalcChecksum(ExecutableImage pe, out uint checkSumPos)
        {
            const uint checksum_pos_in_optional_headers = 64;

            checkSumPos = (uint)pe.NTHeaders.OptionalHeader.Location.FileOffset + checksum_pos_in_optional_headers;

            uint fileSize = (uint)pe.GetBytes().Length;

            MemoryStream ms = new MemoryStream(pe.GetBytes());

            byte[] bytes4 = new byte[4];
            int pos = 0;

            ulong calcSum = 0;
            ulong top = (ulong)0xFFFFFFFF + 1;

            while (ms.Read(bytes4, pos, 4) == 4)
            {
                uint dw = BitConverter.ToUInt32(bytes4, 0);

                if (ms.Position == checkSumPos + 4)
                {
                    continue;
                }

                calcSum = (calcSum & 0xFFFFFFFF) + dw + (calcSum >> 32);
                if (calcSum > top)
                {
                    calcSum = (calcSum & 0xFFFFFFFF) + (calcSum >> 32);
                }
            }

            calcSum = (calcSum & 0xffff) + (calcSum >> 16);
            calcSum = (calcSum) + (calcSum >> 16);
            calcSum = calcSum & 0xffff;

            calcSum += (uint)fileSize;

            return (uint)calcSum;
        }
    }
}

가장 쉬운 사용법은, 빌드한 SetPEChecksum을 여러분들의 프로젝트 설정의 "Build Events" / "Post-build event command line"에 다음과 같이 등록하는 것입니다.

...[path]...\SetPEChecksum.exe /s "$(TargetPath)"

그럼 빌드할 때마다 출력 창에 다음과 같은 메시지를 볼 수 있습니다.

2>  Current Checksum: 0(0x0)
2>  New Checksum: 19088(0x4a90)




이렇게 checksum 파일이 설정된 모듈을 windbg에서 사용하게 되면, 다음과 같이 아주 깔끔한 출력 결과를 볼 수 있습니다.

0:000> !clrstack
OS Thread Id: 0x4370 (0)
        Child SP               IP Call Site
0000003e4f0fea30 00007ffec2dc04c1 SetPEChecksum.Program.Main(System.String[]) [E:\ConsoleApp1\Program.cs @ 15]
0000003e4f0fedb0 00007fff223c6793 [GCFrame: 0000003e4f0fedb0] 

(이 글의 전체 코드는 github에 실려 있습니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/18/2017]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  41  [42]  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12577정성태3/26/202111124개발 환경 구성: 559. Docker Desktop for Windows 기반의 Kubernetes 구성 - WSL 2 인스턴스에 kind 도구로 k8s 클러스터 구성
12576정성태3/25/20218910개발 환경 구성: 558. Docker Desktop for Windows에서 DockerDesktopVM 기반의 Kubernetes 구성 (2) - k8s 서비스 위치
12575정성태3/24/20217994개발 환경 구성: 557. Docker Desktop for Windows에서 DockerDesktopVM 기반의 Kubernetes 구성
12574정성태3/23/202111935.NET Framework: 1030. C# Socket의 Close/Shutdown 동작 (동기 모드)
12573정성태3/22/20219787개발 환경 구성: 556. WSL 인스턴스 초기 설정 명령어 [1]
12572정성태3/22/20219326.NET Framework: 1029. C# - GC 호출로 인한 메모리 압축(Compaction)을 확인하는 방법파일 다운로드1
12571정성태3/21/20218493오류 유형: 706. WSL 2 기반으로 "Enable Kubernetes" 활성화 시 초기화 실패 [1]
12570정성태3/19/202112811개발 환경 구성: 555. openssl - CA로부터 인증받은 새로운 인증서를 생성하는 방법
12569정성태3/18/202111663개발 환경 구성: 554. WSL 인스턴스 export/import 방법 및 단축 아이콘 설정 방법
12568정성태3/18/20217332오류 유형: 705. C# 빌드 - Couldn't process file ... due to its being in the Internet or Restricted zone or having the mark of the web on the file.
12567정성태3/17/20218687개발 환경 구성: 553. Docker Desktop for Windows를 위한 k8s 대시보드 활성화 [1]
12566정성태3/17/20219014개발 환경 구성: 552. Kubernetes - kube-apiserver와 REST API 통신하는 방법 (Docker Desktop for Windows 환경)
12565정성태3/17/20216520오류 유형: 704. curl.exe 실행 시 dll not found 오류
12564정성태3/16/20217006VS.NET IDE: 160. 새 프로젝트 창에 C++/CLI 프로젝트 템플릿이 없는 경우
12563정성태3/16/20218958개발 환경 구성: 551. C# - JIRA REST API 사용 정리 (3) jira-oauth-cli 도구를 이용한 키 관리
12562정성태3/15/202110082개발 환경 구성: 550. C# - JIRA REST API 사용 정리 (2) JIRA OAuth 토큰으로 API 사용하는 방법파일 다운로드1
12561정성태3/12/20218680VS.NET IDE: 159. Visual Studio에서 개행(\n, \r) 등의 제어 문자를 치환하는 방법 - 정규 표현식 사용
12560정성태3/11/202110039개발 환경 구성: 549. ssh-keygen으로 생성한 개인키/공개키 파일을 각각 PKCS8/PEM 형식으로 변환하는 방법
12559정성태3/11/20219432.NET Framework: 1028. 닷넷 5 환경의 Web API에 OpenAPI 적용을 위한 NSwag 또는 Swashbuckle 패키지 사용 [2]파일 다운로드1
12558정성태3/10/20218924Windows: 192. Power Automate Desktop (Preview) 소개 - Bitvise SSH Client 제어 [1]
12557정성태3/10/20217571Windows: 191. 탐색기의 보안 탭에 있는 "Object name" 경로에 LEFT-TO-RIGHT EMBEDDING 제어 문자가 포함되는 문제
12556정성태3/9/20216867오류 유형: 703. PowerShell ISE의 Debug / Toggle Breakpoint 메뉴가 비활성 상태인 경우
12555정성태3/8/20218873Windows: 190. C# - 레지스트리에 등록된 DigitalProductId로부터 라이선스 키(Product Key)를 알아내는 방법파일 다운로드2
12554정성태3/8/20218707.NET Framework: 1027. 닷넷 응용 프로그램을 위한 PDB 옵션 - full, pdbonly, portable, embedded
12553정성태3/5/20219184개발 환경 구성: 548. 기존 .NET Framework 프로젝트를 .NET Core/5+ 용으로 변환해 주는 upgrade-assistant, try-convert 도구 소개 [4]
12552정성태3/5/20218433개발 환경 구성: 547. github workflow/actions에서 Visual Studio Marketplace 패키지 등록하는 방법
... 31  32  33  34  35  36  37  38  39  40  41  [42]  43  44  45  ...