본문 바로가기
OffSec

[Blue Teams Academy] 모듈 18 - Ghidra를 사용한 리버스 엔지니어링 시작

by 10th doctrine 2021. 3. 19.
728x90

이 기사에서는 기드라를 다운로드 받아 설치하고 이를 이용해 역 엔지니어링, 바이너리 분석, 악성코드 분석 등 많은 중요한 작업을 수행하는 방법을 모색해 본다.

소스

그러나 먼저 기드라가 정확히 무엇인가?

Github의 공식 리포지토리에 따르면:

"기드라는 국가안전보위부 조사국(NSE)이 만들고 유지하는 SRE(Software Reverse Engineerframework)이다. 이 프레임워크에는 사용자가 Windows, MacOS, Linux를 포함한 다양한 플랫폼에서 컴파일된 코드를 분석할 수 있는 완전한 기능을 갖춘 고급 소프트웨어 분석 툴 제품군이 포함되어 있다. 기능에는 분해, 조립, 분해, 그래프 작성 및 스크립팅이 포함되며 수백 개의 다른 기능도 포함된다. Ghidra는 다양한 프로세서 명령 집합과 실행 가능한 형식을 지원하며 사용자-인터랙티브 모드와 자동 모드에서 모두 실행할 수 있다. 사용자는 Java 또는 Python을 사용하여 Ghidra 플러그인 구성요소 및/또는 스크립트를 개발할 수도 있다.

기드라는 NSA의 사이버 보안 임무를 지원하기 위해 복잡한 SRE 노력에 대한 확장 및 팀 구성 문제를 해결하고, 사용자 정의가 가능하고 확장 가능한 SRE 연구 플랫폼을 제공하기 위해 구축되었다. NSA는 네트워크와 시스템의 잠재적 취약성에 대한 더 나은 이해를 추구하는 SRE 분석가들을 위해 악의적인 코드 분석과 깊은 통찰력을 생성하는 다양한 문제에 Ghidra SRE 기능을 적용했다.

https://github.com/NationalSecurityAgency/ghidra

이 프로젝트의 공식 웹사이트는 https://ghidra-sre.org이다.

공식 설명에서 알 수 있듯이, 이 도구는 미국 국가안보국(NSA)에 의해 개발되고 유지되어 이 도구의 안전성에 대해 생각하게 한다. 내가 무슨 말을 하는지 몰랐을 경우 이 게시물을 확인하십시오.

C 프로그램을 사용한 컴파일 예제:

이 강력한 도구(Ghidra)로 역 엔지니어링의 기본 원리를 살펴보기 전에 실행 가능한 용어와 몇 가지 중요한 용어를 얻기 위해 컴파일 단계를 살펴보자.

위키피디아는 리버스 엔지니어링을 다음과 같이 정의한다.

"백엔지니어링이라고도 불리는 역엔지니어링은 인간이 만든 물체가 그 설계나 건축, 또는 그 물체로부터 ___지식 추출하기 위해 해체되는 과정이다. 과학연구와 유사하게 과학연구가 자연현상에 관한 것이라는 유일한 차이점이다." _

컴파일러: 하이 레벨 코드를 어셈블리 코드로 변환

조립자: 조립 코드를 기계 코드로 변환

Linkers: 실행 파일을 생성하려면 개체 파일을 가져오십시오.

분해자: 기계코드를 조립코드로 변환

위상은 다음 그래프에 표시된다.

그림

시범적으로 간단한 c 프로그램을 편성해 보자. 가장 잘 알려진 쉬운 프로그램은 단순히 "헬로 월드!" 프로그램이다.

hello.c 프로그램 만들기:

#include <stdio.h> void main(void) { printf ("hello world!\n"); }

이제 그것을 취합하여 gcc와 연결하자.

gcc -o helloWorld hello.c

실행 파일 실행

./helloWorld

Ghidra 설치 방법?

기드라를 사용하기 위해서는 당연히 설치해야 한다. 기술 요구 사항으로 다음이 필요함

하드웨어

  • 4GB 램
  • 1GB 스토리지(설치된 Ghidra 이진 파일용)
  • 듀얼 모니터가 강력하게 제안됨

소프트웨어

  • Java 11 64비트 런타임 및 개발 키트(JDK)

Ghidra v9.1 다운로드로 이동

다운로드 및 Java JDK 설치

설치 폴더로 이동하여 Ghidra bat 파일을 실행하십시오.

설치 단계에 대한 자세한 내용은 Ghidra 공식 문서를 참조하십시오. https://ghidra-sre.org/InstallationGuide.html

역 엔지니어링 예제(CrackMe Challenge):

우리는 완전히 작동하는 바이너리를 만들기 위해 컴파일 단계를 배웠다. 이제 역공학에 대한 기초 지식을 습득하면서 우리의 학습 경험을 계속해야 할 때다. 그렇기 때문에 우리는 작고 쉬운 CrackMe 챌린지를 다운로드 받을 것이며, 도전을 해결할 올바른 암호를 찾기 위해 무엇을 하고 있는지, 어떻게 작동하는지 이해하려고 노력할 것이다.

우리가 해결할 과제는 이 무료 및 공개 교육 자료의 일부분이다. https://github.com/Maijin/Workshop2015

우리는 여기서 드래곤: 기드라와 역 엔지니어링을 따를 것이다.

GitHub 저장소를 다운로드하고 /IOLI-crackme/bin-win32로 이동하면 챌린지 바이너리를 찾을 수 있다.

우리는 "Crackme0x01" 파일을 되돌릴 것이다.

명령줄 터미널을 사용하여 직접 열자:

이진 폴더를 입력하고 다음을 입력하십시오.

Crackme0x01.exe

임의의 암호를 입력하십시오. 내 경우 "root"를 입력했지만 "잘못된 암호!" 오류 메시지가 표시됨

그럼 한번 해보자.

오픈 기드라

새 프로젝트 시작:

프로젝트 이름 지정

배치 가져오기를 사용하여 이진 가져오기

이진 열기

필요한 옵션을 선택하고 "분석"을 클릭하십시오.

Vaila! 이것이 기드라의 주요 창이다.

함수 그래프를 확인할 수도 있다.

문제를 해결하려면 먼저 이진 문자열 추출부터 시작하십시오.

너도 알다시피 우리는 그 파일의 모든 끈을 얻는다. 그 중 하나가 "Password OK :"이다.

기드라는 힘이 있다. 파일을 압축 해제할 수 있는 기능을 제공한다. 스크린샷에서 볼 수 있듯이, 그것은 우리에게 읽을 수 있는 코드를 주고 있다.

만약 당신이 코드를 주의깊게 확인한다면 당신은 이 코드 라인을 발견할 것이다.

If (local_8 == 0x149a) _Printf ( “Password OK :) /n ”)

창 반대편에 CMP 지침이 보일 것이다. 작은 구글 검색으로 당신은 그것을 찾을 수 있을 것이다.

"CMP는 일반적으로 조건부 실행에 사용된다. 이 __ 명령어 기본적으로 피연산자가 동일한지 여부를 비교하기 위해 피연산자를 다른 피연산자에서 뺀다. 대상 또는 소스 피연산자를 방해하지 않는다. 그것은 의사결정을 위해 조건부 점프 _ 명령 _과 함께 사용된다. "

만약 우리의 분석이 정확하다면, 유효한 비밀번호는 "0x149a"의 변환이 될 것이다.

값을 확인하려면 해당 값을 두 번 클릭하면 이 메시지가 나타난다.

소수점 값은 "5274"이다. 그러니 한번 해보자:

터미널로 돌아가서 바이너리를 실행하고 이번에는 5274:

축하해, 첫 번째 크랙미 도전을 해결했구나.

이 문서는 Ghidra를 사용한 멀웨어 분석과 같은 보다 흥미로운 섹션으로 업데이트될 것이다.

추가 자원

참조

요약

이 글은 '기드라'라는 놀라운 도구로 역공학의 기초를 배울 수 있는 좋은 기회였다.

 

더보기

Getting Started with Reverse Engineering using Ghidra

In this article, we are going to explore how to download Ghidra, install it and use it to perform many important tasks such as reverse engineering, binary analysis and malware analysis.

Source

But first what is Ghidra exactly?

According to its official Github repository:

"Ghidra is a software reverse engineering (SRE) framework created and maintained by the National Security AgencyResearch Directorate. This framework includes a suite of full-featured, high-end software analysis tools that enable users to analyze compiled code on a variety of platforms including Windows, macOS, and Linux. Capabilities include disassembly, assembly, decompilation, graphing, and scripting, along with hundreds of other features. Ghidra supports a wide variety of processor instruction sets and executable formats and can be run in both user-interactive and automated modes. Users may also develop their own Ghidra plug-in components and/or scripts using Java or Python.

In support of NSA's Cyber Security mission, Ghidra was built to solve scaling and teaming problems on complex SRE efforts, and to provide a customizable and extensible SRE research platform. NSA has applied Ghidra SRE capabilities to a variety of problems that involve analyzing malicious code and generating deep insights for SRE analysts who seek a better understanding of potential vulnerabilities in networks and systems.

https://github.com/NationalSecurityAgency/ghidra

The official website of the project is https://ghidra-sre.org:

As you can notice from the official description that this tool was developed and maintained by the US NSA (National Security Agency) which leads us to think about if this tool is secure. Check this post if you didn't know what i am talking about:

Compilation example with a C Program:

Before diving into the fundamentals of reverse engineering with this powerful tool (Ghidra) , let's explore the compiling phases in order to get an executable and some important terminologies.

Wikipedia defines Reverse engineering as follows:

"_Reverse engineering, also called back engineering, is the process by which a human-made object is deconstructed to reveal its designs, architecture , or to extract knowledge __from the object; similar to scientific research, the only difference being that scientific research is about a natural phenomenon." _

Compilers: convert high-level code to assembly code

Assemblers: convert assembly code to machine code

Linkers: take the object files in order to generate the executable

Disassemblers: convert machine code to assembly code

The phases are represented in the following graph:

Figure

As a demonstration, let's compile a simple c program. The most known easy program is simply a " hello world!" program

Create a hello.c program:

#include <stdio.h> void main(void) { printf ("hello world!\n"); }

Now let's compile it and link it with gcc

gcc -o helloWorld hello.c

Run the executable

./helloWorld

How to install Ghidra?

To use Ghidra we need to install it of course. As technical requirements, you need the following

Hardware

  • 4 GB RAM
  • 1 GB storage (for installed Ghidra binaries)
  • Dual monitors strongly suggested

Software

  • Java 11 64-bit Runtime and Development Kit (JDK)

Go to Download Ghidra v9.1

Download it and install Java JDK

Go to the installation folder and run the Ghidra bat file

For more information about the installation steps you can check Ghidra official documentation: https://ghidra-sre.org/InstallationGuide.html

Reverse engineering example (CrackMe Challenge):

We learned the compilation phases in order to generate a fully working binary. Now it is time to continue our learning experience with acquiring some fundamentals about reverse engineering. That is why we are going to download a small and easy CrackMe challenge and we will try to understand what is doing and how it works in order to find the correct password to solve the challenges.

The challenge that we are going to solve is a part of this free and publicly available training materials: https://github.com/Maijin/Workshop2015

We are going to follow Here Be Dragons: Reverse Engineering with Ghidra

Download the GitHub repository, go to /IOLI-crackme/bin-win32 and you will find the challenge binaries.

We are going to reverse " Crackme0x01" file.

Let's open it directly using the command line terminal:

Enter the binaries folder and type:

Crackme0x01.exe

Enter a random password. In my case I entered "root" but i get an "Invalid Password!" error message

Then let's crack it

Open Ghidra

Start a new project:

Name the project

Import the binary with Batch Import

Open the binary

Select the required options and click "Analyze"

Voila! This is the main windows of Ghidra

You can also check the function graphs

To solve the challenge let's first start with extracting the binary strings

As you can notice we get all the strings of the file. One of them is "Password OK :)"

Ghidra is powerful. It gives you the ability to decompile the file. As you can see from the screenshot it is giving us a readable code.

If you check the code carefully you will notice this line of code

If (local_8 == 0x149a) _Printf ( “Password OK :) /n ”)

At the other side of the window you will see the CMP instruction. With a small Google search you will find that

"CMP is generally used in conditional execution. This __ _ instruction _ basically subtracts one operand from the other for comparing whether the operands are equal or not. It does not disturb the destination or source operands. It is used along with the conditional jump _ instruction _ __ for decision making. "

Then if our analysis is correct then the valid password will be a conversion of "0x149a"

To check its value double click on it and you will get this.

The decimal value is "5274". So let's try it:

Go back to your terminal and run the binary and this time type 5274:

Congratulations, you solved your first crackme challenge.

This article will be updated with more interesting sections in the next few hours like Malware Analysis with Ghidra

Further resources

References

Summary

This article was a good opportunity to learn the fundamentals of reverse engineering with an amazing tool called "Ghidra"

 

 

※ 출처 : Blue Teams Academy | www.blueteamsacademy.com/ghidra/

반응형

댓글