es
Feedback

¡No caigas en manos de tramposos! Telemetrio encuentra y marca estos canales 👉 Si quieres ver la etiqueta, suscríbete

ReverseEngineering

ReverseEngineering

Ir al canal en Telegram
1 730
Suscriptores
-124 horas
-47 días
+28230 días
Archivo de publicaciones
Round Robin و تقسیم زمان CPU بین Process ها اگر ندونیم هر Job چقدر زمان CPU نیاز داره، چطور می‌تونیم به همه فرصت مناسبی برای اجرا بدیم؟ اینجاست که الگوریتم Round Robin وارد میشه ایده اصلی Round Robin در Round Robin به هر Job یک بازه زمانی مشخص اختصاص میدیم به این بازه میگیم Time Slice یا Time Quantum مثلا فرض کنید Time Quantum برابر 10ms باشه هر Job حداکثر 10ms فرصت اجرا داره اگر در این مدت تموم نشه اجرای اون متوقف میشه و به اخر صف Ready برمیگرده بعد Scheduler سراغ Job بعدی میره ساختار کلی
Ready Queue
    |
    v
  Job A
    |
    v
  CPU (10ms)
    |
    +---- Finished
    |         |
    |         v
    |      خارج  از صف
    |
    +---- Not Finished
              |
              v
         اخر صف
              |
              v
            Job B
یک مثال ساده سه Job داریم
A = 24ms
B = 3ms
C = 3ms
همه در زمان صفر وارد سیستم شدن فرض میکنیم
Time Quantum = 4ms
صف اولیه
A → B → C
حالا اجرا رو شروع می‌کنیم اجرای A ابتدا A به مدت 4ms اجرا میشه
A Remaining = 20ms
چون هنوز تموم نشده، به انتهای صف میره
B → C → A
اجرای B حالا B نوبت اجرا میگیره چون فقط 3ms زمان CPU نیاز داره قبل از تموم‌ شدن Quantum کارش تموم میشه
B Finished
صف
C → A
اجرای C C هم فقط 3ms زمان نیاز داره پس اجرای اون هم تموم میشه
C Finished
صف
A
اجرای دوباره A حالا A دوباره CPU رو دریافت میکنه این بار هم 4ms اجرا میشه
A Remaining = 16ms
چون هنوز تموم نشده دوباره به انتهای صف برمیگرده از اونجایی که فقط A باقی مونده، در نوبت بعدی دوباره خودش CPU رو دریافت میکنه بررسی Timeline کامل
0    4    7    10   14   18   22   26   30
|----|----|----|----|----|----|----|----|
  A    B    C    A    A    A    A    A
در این مثال A در چند نوبت اجرا میشه B در اولین نوبت خودش تموم میشه C هم در اولین نوبت خودش تموم میشه زمان پایان هر Job
A = 30ms
B = 7ms
C = 10ms
چون همه در زمان صفر وارد سیستم شدن Turnaround Time برابر زمان Completion هر Job هست
A = 30ms
B = 7ms
C = 10ms
میانگین Turnaround Time
(30 + 7 + 10) / 3

= 15.67ms
دقت کنید که در این مثال فرض کردیم سربار Context Switch نداریم و ترتیب اولیه صف هم مشخصه چرا Round Robin برای سیستم‌ های تعاملی مناسبه؟ فرض کنید چند برنامه همزمان در حال اجرا هستن
Browser
Terminal
Text Editor
Music Player
اگر یک برنامه مدت زیادی CPU رو اشغال کنه بقیه برنامه‌ها ممکنه پاسخ‌گویی مناسبی نداشته باشن Round Robin تلاش میکنه CPU رو بین Job های آماده تقسیم کنه به این ترتیب هر Job فرصت پیدا میکنه در بازه‌های زمانی مشخص اجرا بشه البته این به معنی اجرای همزمان واقعی روی یک Core نیست بلکه CPU خیلی سریع بین Job ها جا به‌ جا میشه و به هرکدوم فرصت اجرا میده Time Quantum چه اهمیتی داره؟ یکی از مهم‌ترین پارامترهای Round Robin مقدار Time Quantum هست فرض کنید
Quantum = 1ms
در این حالت جا به‌ جایی‌ ها زیاد میشن
A → B → C → A → B → C
این موضوع میتونه باعث افزایش هزینه Context Switch بشه حالا فرض کنید
Quantum = 1000ms
در این حالت هر Job مدت زیادی CPU رو در اختیار داره پس پاسخ‌گویی به Job های دیگه ممکنه ضعیف بشه بنابراین باید بین دو موضوع تعادل برقرار کنیم
Quantum کوچک
     |
     v
نوبت‌ های کوتاه‌ تر
     |
     v
Context Switch بیشتر
و
Quantum بزرگ
     |
     v
نوبت‌ های طولانی‌ تر
     |
     v
Context Switch کمتر
در نتیجه انتخاب Quantum روی میزان سربار و پاسخ‌ گویی سیستم تأثیر مستقیم داره ارتباط Quantum با Response Time فرض کنید N عدد Job آماده اجرا داریم و همه اون‌ها در یک صف Round Robin قرار گرفتن اگر همه Job ها به اندازه کامل Quantum اجرا بشن در حالت ساده و با فرض نبود سربار یک Job تقریباً بعد از گذشت زمان زیر دوباره نوبت اجرا میگیره
(N - 1) × Quantum
مثلا
N = 4
Quantum = 10ms
پس
(4 - 1) × 10 = 30ms
یعنی بعد از اجرای سه Job دیگه نوبت Job اول دوباره میرسه البته این محاسبه برای شرایط ساده‌ ایه که Jobها همچنان آماده اجرا باقی بمونن و قبل از پایان Quantum از صف خارج نشن Round Robin همیشه بهترین انتخابه؟ خیر Round Robin برای پاسخ‌ گویی مناسب طراحی شده اما حتما میانگین Turnaround Time رو به حداقل نمیرسونه
20 nov, 14:02

readelf -S program
To view file sections
objdump -h program
To check sections
objdump -d program
For Disassembly In Windows, we can also use tools such as the following
dumpbin WinDbg
To check executable file information and run-time analysis In Binary analysis, we should not be limited to Instructions only Some of the important information related to how the program is executed may be stored in Metadata For Windows x64
.pdata | v RUNTIME_FUNCTION | v .xdata | v UNWIND_INFO | v Unwind / Handler Information
For Linux
.eh_frame | +---- CIE | +---- FDE | v CFI
And for Exception Handling in C++
.gcc_except_table | v LSDA | +---- Call-Site Table +---- Action Table +---- Type Table
Our goal is to combine this information with Disassembly to create a more accurate picture of how the program executes and the different Control Flow paths @reverseengine
20 nov, 13:13

Landing Pad / Handler / Cleanup This allows us to better understand the program's non-standard execution paths. An important point is that metadata does not always provide a complete, ready-to-use Control Flow Graph (CFG). It must be combined with disassembly, cross-references, and function analysis. Furthermore, in some implementations, exception paths do not appear directly within the standard instruction flow of a function; they must be reconstructed using the metadata. Useful tools for analysis: In addition to Ghidra, the following tools are also useful for examining metadata:
readelf -wf program
For inspecting Frame Information in ELF files.
20 nov, 13:10

In general:
UNW_FLAG_EHANDLER
Indicates that information regarding an Exception Handler is present.
UNW_FLAG_UHANDLER
Indicates that information regarding a Termination Handler is present.
UNW_FLAG_CHAININFO
Indicates that the unwind information is chained to another RUNTIME_FUNCTION. If a handler-related flag is set, additional information is placed after the unwind codes. In such cases, the structure associated with the handler—along with its specific data—must also be analyzed. Note that the presence of these flags does not mean the handler code itself is located within the
.xdata section. Rather, this information assists the unwinder in locating the appropriate handler and retrieving the necessary data. Examining .eh_frame in Linux: Now, assume the binary is in ELF format. In this context, one of the significant sections is: .eh_frame This section contains information used for unwinding stack frames. Two key structures within this section are:
CIE FDE CIE
Stands for "Common Information Entry." It stores general information regarding the unwinding process. FDE Stands for "Frame Description Entry." This structure holds information pertaining to a specific range of code and typically references a CIE. Conceptually:
.eh_frame
| +---- CIE | +---- FDE | +---- FDE | +---- FDE Each FDE can be associated with a CIE. Consequently, general information can be reused across multiple functions. What is CFI? One of the key concepts in analyzing .eh_frame is Call Frame Information, or CFI. CFI specifies how the state of registers and the stack frame should be reconstructed at various points during a function's execution. For instance, within the unwind information, we might encounter an expression such as:
CFA = rsp + 8
Here, CFA stands for Canonical Frame Address. This refers to the address used as a reference point to reconstruct the frame state. Since the value of the CFA and the storage locations of registers can shift as different instructions are executed, CFI is not a static description that applies to the entire function. Unwind rules may evolve throughout the execution of a function. Consequently, it is necessary to examine changes in the CFI at different offsets within the function. Analyzing the LSDA and Exception Table In C++ binaries that adhere to the Itanium C++ ABI, information regarding the selection of exception handlers is typically described via a structure known as the LSDA. In certain ELF files, this data can be found in sections such as: .gcc_except_table LSDA stands for Language Specific Data Area. This structure may contain components such as:
Call-Site Table Action Table Type Table
Each of these plays a distinct role in determining how exceptions are handled. * Call-Site Table: Identifies which exception-handling data applies to specific code ranges, and determines which action or "landing pad" should be invoked if an exception occurs. * Action Table: Stores information regarding the chain of actions and the logic for selecting an appropriate handler. * Type Table: Contains information about exception types, allowing the system to determine which handlers correspond to specific types of exceptions. Note that the precise structure of the LSDA depends on the ABI and the specific runtime implementation. By leveraging this information, we can determine how an exception is managed within a given range of a function. How is this information... ...connect it to the Control Flow? Consider a structure like this within a function:
void execute() { Resource resource; try { operation(); } catch (...) { handle_error(); } }
In the disassembly, we might only see a portion of the function's logic. However, by examining the metadata, we discover that a specific range of instructions is covered by exception handling. Now, we can piece several components together:
Disassembly | v Function Range | v Exception Metadata | v
20 nov, 13:10

Handler inspection on Windows x64 In some functions, the unwind information does not only include operations related to the stack. It is possible that the handler or information related to exception handling also exist In this case, the flags of the
UNWIND_INFO structure become important UNW_FLAG_EHANDLER UNW_FLAG_UHANDLER UNW_FLAG_CHAININFO
20 nov, 13:07

Analyzing Exception Metadata in Ghidra and Reconstructing Control Flow Why should we examine Metadata? In the previous section, we saw that the Compiler generates information outside the normal flow of Assembly instructions to handle exceptions. This information can specify Where is the address range of a function
Stack Frame
How should it be rebuilt What path should be taken if an exception occurs Which sections need cleanup What handlers are responsible for handling exceptions Now suppose we have an unknown Binary and we want to extract this information First we need to know what type of Binary and ABI we are dealing with Because the structure of Exception Handling in Windows x64 and Linux is not the same Starting analysis in Ghidra First we open the Binary in Ghidra In the first step, we check this information
Format Architecture Compiler Sections Imported Symbols
For example, we may encounter a PE file related to Windows x64 In this case, one of the first sections to check is .pdata And then there is information that is usually located in the following section They take .xdata But if we are dealing with a Linux ELF file, we should look for information like this .eh_frame .gcc_except_table This difference is important because if we analyze the structure of one ABI with the assumptions of another ABI, our conclusions will be wrong .pdata inspection on Windows x64 On Windows x64, the .pdata section usually contains an array of RUNTIME_FUNCTION structures Each Entry has three main values typedef struct
_RUNTIME_FUNCTION { DWORD BeginAddress; DWORD EndAddress; DWORD UnwindInfoAddress; } RUNTIME_FUNCTION;
These addresses are usually stored in RVA format For example
BeginAddress = 0x1000 EndAddress = 0x1080
UnwindInfoAddress = 0x3000 That is Function Range:
0x1000 - 0x1080
Unwind Information:
0x3000
If ImageBase is suppose to be
0x140000000
Function Start =
ImageBase + 0x1000 Function End = ImageBase + 0x1080 Unwind Info = ImageBase + 0x3000
In practice, we need to make sure that the values ​​are really RVA and match the Section Mapping of the file The important point is that RUNTIME_FUNCTION only specifies the function scope and location of the Unwind information and does not include Assembly instructions or Handler code
RUNTIME_FUNCTION relationship with UNWIND_INFO
Now suppose we find an Entry in .pdata We need to look for the value of UnwindInfoAddress Let's do This address points to a structure that holds the Unwind function information Its conceptual structure is as follows
typedef struct _UNWIND_INFO { BYTE Version : 3; BYTE Flags : 5; BYTE SizeOfProlog; BYTE CountOfCodes; BYTE FrameRegister : 4; BYTE FrameOffset : 4; UNWIND_CODE UnwindCode[1]; } UNWIND_INFO;
This structure holds information about the function's Prologue and the operations performed on the Stack For example, if the function has such instructions
push rbx sub rsp, 0x40
The Unwind information should allow the reconstruction of the previous state of the Stack and the saved registers So when we compare Metadata with Disassembly, we can understand how the Compiler managed the Stack Frame
UNWIND_CODE
What information does it contain? Each Unwind Code describes a specific operation. Some common operations are:
UWOP_PUSH_NONVOL UWOP_ALLOC_SMALL UWOP_ALLOC_LARGE UWOP_SET_FPREG UWOP_SAVE_NONVOL UWOP_SAVE_NONVOL FAR For example, UWOP_PUSH_NONVOL
describes the operation of saving a nonvolatile register to the stack, and UWOP_ALLOC_SMALL is used to describe the allocation of a relatively small amount of space to the stack. The important thing is that this information is used to reconstruct the previous state of the stack. That is, the unwinder must be able to understand what operation was performed to return the function execution state to the appropriate state. Unwind Codes are also stored in a specific order and their information is dependent on the Offset related to the prologue. So when analyzing, we must also consider the order and location of each operation.
20 nov, 13:07

readelf -S program
برای مشاهده Section های فایل
objdump -h program
برای بررسی Section ها
objdump -d program
برای Disassembly در Windows هم میتونیم از ابزارهایی مثل موارد زیر استفاده کنیم
dumpbin
WinDbg
برای بررسی اطلاعات فایل اجرایی و تحلیل زمان اجرا در تحلیل Binary نباید فقط به Instruction ها محدود بشیم بخشی از اطلاعات مهم مربوط به نحوه اجرای برنامه ممکنه در Metadata ذخیره شده باشه برای Windows x64
.pdata
   |
   v
RUNTIME_FUNCTION
   |
   v
.xdata
   |
   v
UNWIND_INFO
   |
   v
Unwind / Handler Information
برای Linux
.eh_frame
   |
   +---- CIE
   |
   +---- FDE
   |
   v
CFI
و برای Exception Handling در ++C
.gcc_except_table
   |
   v
LSDA
   |
   +---- Call-Site Table
   +---- Action Table
   +---- Type Table
هدف ما اینه که با ترکیب این اطلاعات و Disassembly تصویر دقیق‌ تری از نحوه اجرای برنامه و مسیرهای مختلف Control Flow بسازیم @reverseengine
20 nov, 13:03

به‌صورت کلی UNW_FLAG_EHANDLER نشون میده اطلاعات مربوط به Exception Handler وجود داره UNW_FLAG_UHANDLER نشون میده اطلاعات مربوط به Termination Handler وجود داره UNW_FLAG_CHAININFO نشون میده اطلاعات Unwind به یک RUNTIME_FUNCTION دیگه زنجیر شده اگر Flag مربوط به Handler فعال باشه اطلاعات اضافی بعد از Unwind Codes قرار میگیرن در این شرایط باید ساختار مربوط به Handler و داده‌ های اختصاصی اون رو هم تحلیل کنیم دقت کنید که وجود این Flag ها به معنی قرار داشتن خود کد Handler داخل .xdata نیست این اطلاعات بیشتر به Unwinder کمک می‌کنن تا Handler مناسب و اطلاعات موردنیاز رو پیدا کنه بررسی .eh_frame در Linux حالا فرض کنید Binary از نوع ELF باشه در این حالت یکی از بخش‌های مهم
.eh_frame
هست این بخش شامل اطلاعاتی برای Unwind کردن Stack Frameهاست دو ساختار مهم در این بخش
CIE
FDE
هستن CIE مخفف Common Information Entry هست اطلاعات عمومی مربوط به نحوه Unwind رو نگه میداره FDE مخفف Frame Description Entry هست این ساختار اطلاعات مربوط به محدوده مشخصی از کد رو نگه میداره و معمولا به یک CIE ارجاع میده به‌صورت مفهومی
.eh_frame
    |
    +---- CIE
    |
    +---- FDE
    |
    +---- FDE
    |
    +---- FDE
هر FDE میتونه به یک CIE مرتبط باشه در نتیجه اطلاعات عمومی بین چند Function قابل استفاده مجدد هست CFI چیه؟ یکی از مفاهیم مهم در تحلیل .eh_frame عبارت Call Frame Information یا همون CFI هست CFI مشخص میکنه وضعیت Register ها و Stack Frame در نقاط مختلف اجرای تابع چطور باید بازسازی بشه برای مثال ممکنه در اطلاعات Unwind ببینیم
CFA = rsp + 8
CFA مخفف Canonical Frame Address هست این مفهوم به آدرسی اشاره میکنه که برای بازسازی وضعیت Frame ازش استفاده میشه با اجرای دستور های مختلف مقدار CFA و محل ذخیره Register ها ممکنه تغییر کنه پس CFI صرفا یک توضیح ثابت برای کل تابع نیست ممکنه در طول اجرای تابع قوانین Unwind تغییر کنن برای همین باید تغییرات CFI رو در Offset های مختلف تابع بررسی کنیم بررسی LSDA و Exception Table در Binaryهای ++C که از Itanium C++ ABI استفاده میکنن اطلاعات مربوط به انتخاب Handler ها معمولا از طریق ساختاری به اسم LSDA توصیف میشه این اطلاعات در بعضی فایل‌های ELF در بخش‌ هایی مثل
.gcc_except_table
قابل مشاهده هستن LSDA مخفف Language Specific Data Area هست این ساختار میتونه شامل اطلاعاتی مثل موارد زیر باشه
Call-Site Table
Action Table
Type Table
هرکدوم نقش متفاوتی در تعیین رفتار Exception دارن Call-Site Table مشخص میکنه محدوده‌ های مشخصی از کد تحت پوشش چه اطلاعاتی از Exception Handling قرار دارن و در صورت وقوع Exception چه Action یا Landing Pad ای باید در نظر گرفته بشه Action Table اطلاعات مربوط به زنجیره Action ها و نحوه انتخاب Handler رو نگه میداره Type Table میتونه اطلاعات مربوط به Type های Exception رو در خودش داشته باشه تا مشخص بشه چه Handler هایی با چه نوع Exception هایی مطابقت دارن البته ساختار دقیق LSDA به ABI و نحوه پیاده‌سازی Runtime وابسته است به کمک این اطلاعات میتونیم بفهمیم یک Exception در محدوده مشخصی از تابع چطور مدیریت میشه چطور این اطلاعات رو به Control Flow وصل کنیم؟ فرض کنید در یک تابع چنین ساختاری داریم
void execute() {
    Resource resource;

    try {
        operation();
    }
    catch (...) {
        handle_error();
    }
}
در Disassembly ممکنه فقط بخشی از منطق تابع رو ببینیم اما وقتی Metadata رو بررسی میکنیم متوجه میشیم که یک محدوده مشخص از دستورها تحت پوشش Exception Handling قرار گرفته حالا میتونیم چند بخش رو کنار هم قرار بدیم
Disassembly
    |
    v
Function Range
    |
    v
Exception Metadata
    |
    v
Landing Pad / Handler / Cleanup
این کار باعث میشه مسیرهای اجرای غیرعادی برنامه رو بهتر درک کنیم نکته مهم اینه که Metadata همیشه یک CFG کامل و آماده در اختیارمون نمیذاره باید اون رو با Disassembly و Cross-Reference و تحلیل توابع ترکیب کنیم همچنین در بعضی پیاده‌سازی‌ ها مسیر های Exception به شکل مستقیم در جریان عادی دستورهای تابع دیده نمیشن و باید با استفاده از Metadata اون‌ها رو بازسازی کنیم چند ابزار مفید برای تحلیل علاوه بر Ghidra، ابزارهای زیر هم برای بررسی Metadata کاربرد دارن
readelf -wf program
برای بررسی Frame Information در ELF
20 nov, 13:03

تحلیل Exception Metadata در Ghidra و بازسازی Control Flow چرا باید Metadata رو بررسی کنیم؟ در قسمت قبل دیدیم که Compiler برای مدیریت Exception ها اطلاعاتی خارج از جریان عادی دستورهای Assembly تولید میکنه این اطلاعات میتونن مشخص کنن محدوده آدرس‌ های متعلق به یک تابع کجاست Stack Frame چطور باید بازسازی بشه در صورت اتفاق افتادن Exception چه مسیری باید طی بشه کدوم بخش‌ها نیاز به Cleanup دارن چه Handlerهایی مسئول رسیدگی به Exception هستن حالا فرض کنید یک Binary ناشناخته داریم و میخوایم این اطلاعات رو استخراج کنیم اول باید بدونیم با چه نوع Binary و ABIای روبه‌رو هستیم چون ساختار Exception Handling در Windows x64 و Linux یکسان نیست شروع تحلیل در Ghidra ابتدا Binary رو در Ghidra باز میکنیم در مرحله اول این اطلاعات رو بررسی می‌کنیم
Format Architecture Compiler Sections Imported Symbols
برای مثال ممکنه با یک فایل PE مربوط به Windows x64 مواجه بشیم در این حالت یکی از اولین بخش‌هایی که باید بررسی کنیم
.pdata
و بعد اطلاعاتی هست که معمولا در بخش زیر قرار میگیرن
.xdata
اما اگر با یک فایل ELF مربوط به Linux رو به‌ رو باشیم باید دنبال اطلاعاتی مثل این بگردیم
.eh_frame
.gcc_except_table
این تفاوت مهمه چون اگر ساختار یک ABI رو با فرضیات ABI دیگه تحلیل کنیم نتیجه‌گیری‌ هامون اشتباه میشه بررسی .pdata در Windows x64 در Windows x64، بخش .pdata معمولاً شامل آرایه‌ای از ساختارهای RUNTIME_FUNCTION هست هر Entry سه مقدار اصلی داره
typedef struct _RUNTIME_FUNCTION {
    DWORD BeginAddress;
    DWORD EndAddress;
    DWORD UnwindInfoAddress;
} RUNTIME_FUNCTION;
این آدرس‌ ها معمولا به شکل RVA ذخیره میشن برای مثال
BeginAddress       = 0x1000
EndAddress         = 0x1080
UnwindInfoAddress  = 0x3000
یعنی
Function Range:
0x1000 - 0x1080

Unwind Information:
0x3000
اگر ImageBase فرضا برابر 0x140000000 باشه
Function Start =
ImageBase + 0x1000

Function End =
ImageBase + 0x1080

Unwind Info =
ImageBase + 0x3000
در عمل باید مطمئن بشیم مقادیر واقعا RVA هستن و با Section Mapping فایل تطبیق دارن نکته مهم اینه که RUNTIME_FUNCTION فقط محدوده تابع و محل اطلاعات Unwind رو مشخص میکنه و خودش شامل دستورهای Assembly یا کد Handler نیست ارتباط RUNTIME_FUNCTION با UNWIND_INFO حالا فرض کنید یک Entry در .pdata پیدا کردیم باید مقدار UnwindInfoAddress رو دنبال کنیم این آدرس به ساختاری اشاره میکنه که اطلاعات Unwind تابع رو نگه میداره ساختار مفهومی اون به این شکله
typedef struct _UNWIND_INFO {
    BYTE Version : 3;
    BYTE Flags : 5;
    BYTE SizeOfProlog;
    BYTE CountOfCodes;
    BYTE FrameRegister : 4;
    BYTE FrameOffset : 4;
    UNWIND_CODE UnwindCode[1];
} UNWIND_INFO;
این ساختار اطلاعاتی درباره Prologue تابع و عملیات انجام‌ شده روی Stack نگه میداره مثلا اگر تابع همچین دستور هایی داشته باشه
push rbx
sub rsp, 0x40
اطلاعات Unwind باید امکان بازسازی وضعیت قبلی Stack و Register های ذخیره‌شده رو فراهم کنه بنابراین وقتی Metadata رو با Disassembly مقایسه میکنیم میتونیم بفهمیم Compiler چطور Stack Frame رو مدیریت کرده UNWIND_CODE چه اطلاعاتی داره؟ هر Unwind Code یک عملیات مشخص رو توصیف میکنه بعضی از عملیات‌ های رایج
UWOP_PUSH_NONVOL
UWOP_ALLOC_SMALL
UWOP_ALLOC_LARGE
UWOP_SET_FPREG
UWOP_SAVE_NONVOL
UWOP_SAVE_NONVOL_FAR
برای مثال UWOP_PUSH_NONVOL عملیات ذخیره یک Nonvolatile Register روی Stack رو توصیف میکنه و UWOP_ALLOC_SMALL برای توصیف اختصاص فضای نسبتا کوچک به Stack کاربرد داره نکته مهم اینه که این اطلاعات برای بازسازی وضعیت قبلی Stack استفاده میشن یعنی Unwinder باید بتونه بفهمه چه عملیاتی انجام شده تا وضعیت اجرای تابع رو به حالت مناسب برگردونه همچنین Unwind Code ها به ترتیب مشخصی ذخیره میشن و اطلاعات اونها به Offset مربوط به Prologue وابسته است پس هنگام تحلیل باید ترتیب و محل اجرای هر عملیات رو هم در نظر بگیریم بررسی Handler در Windows x64 در بعضی توابع اطلاعات Unwind فقط شامل عملیات مربوط به Stack نیست ممکنه Handler یا اطلاعات مربوط به Exception Handling هم وجود داشته باشه در این حالت Flag های ساختار UNWIND_INFO اهمیت پیدا میکنن
UNW_FLAG_EHANDLER
UNW_FLAG_UHANDLER
UNW_FLAG_CHAININFO
20 nov, 13:03

This identifier is useful for grouping events related to a Process and largely solves the problem of using PID alone For example:
Process Create

ProcessGuid: {AAAA}
ProcessId: 4520
Image: app.exe
A few moments later:
Network Connection

ProcessGuid: {AAAA}
ProcessId: 4520
DestinationIp: 192.0.2.10
Now we can understand that the network connection was related to the same Process as before Creating a chain of Process behavior The real power of Telemetry becomes clear when we examine several events together Suppose a Process is created and then performs various activities
Process Create
Event ID 1
|
v
Image Loaded
Event ID 7
|
v
DNS Query
Event ID 22
|
v
Network Connection
Event ID 3
|
v
Process Access
Event ID 10
|
 v
Process Terminated
Event ID 5
By putting these events together, we can get a fairly complete view of the Process' behavior Of course, this chain alone is not a sign of malware A completely normal program may also produce these events. What matters is the relationship between the events and the context in which they occur What is Sysmon Configuration? Sysmon uses a Configuration file to know what events to record This file is usually written in XML format Inside the Configuration, we specify: Which Events to record Which Processes to include in the monitoring Which paths to check Which events to exclude from recording For example, we may want to record only the activity related to a number of specific Processes Here, Include and Exclude Filters are used The important point is that if the Configuration is too restrictive, we may miss important events On the other hand, if we record everything without filtering, a large volume of logs will be generated and its analysis will be more difficult So, designing the Configuration itself is considered part of the Detection Engineering task Exercise: To better understand these concepts, perform these steps on a lab machine. Step 1 Download Sysmon from the official Microsoft Sysinternals source: [Microsoft Sysmon Documentation](https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon?utm_source=chatgpt.com) Step 2 Install Sysmon with a valid and basic configuration on the lab machine Step 3 Run Notepad Step 4 Go to Event Viewer and open the following path:
Applications and Services Logs
|
└── Microsoft
|
└── Windows
|
└── Sysmon
|
 └── Operational
Step 5 Find the Event ID 1 event and check these fields:
Image
ProcessId
ProcessGuid
CommandLine
ParentImage
ParentProcessId
ParentCommandLine
Now close Notepad and check if Event ID 5 is also recorded If Event IDs related to DNS and Network Connection are enabled in Configuration, you can check them too Sysmon Limitations Sysmon is a powerful tool but it also has limitations: It does not record all system activities Some Events require configuration Large log size can make analysis difficult Some events may also be seen in normal software Recording an Event alone does not prove that it was a malicious activity So in security analysis, we should not rely only on an Event ID We should examine the behavior of the parent Process of that Command Line at runtime and related events together @reverseengine
17 nov, 02:48

Sysmon and Process Telemetry So far, we have been introduced to ETW and seen how Windows records various system events and makes them available to monitoring tools Now we want to move on to one of the important tools in analyzing process behavior, namely Sysmon Sysmon It helps us understand what happened inside the system and what activities the processes were doing Sysmon System Monitor is one of the tools in the Microsoft Sysinternals suite that monitors various system activities and records information about them in the Windows Event Log For example, it can record information about the following: Creation and termination of processes Creation of child processes Uploading DLLs and images Network communications Access of one process to another Registry changes File creation DNS requests An important point: Sysmon itself is not an EDR or malware detection engine Its main task is to collect and record Telemetry Security tools can use this information to analyze system behavior and identify Suspicious activities use The difference between ETW, Event Log and Sysmon These three concepts are related but do not have the same meaning Path to view Sysmon events:
Event Viewer
|
└── Applications and Services Logs
|
└── Microsoft
|
└── Windows
|
└── Sysmon
|
└── Operational
Getting to know important Event IDs Each event that Sysmon records has a specific Event ID Some important ones: | Event ID | Event | | -------- | ----------------------------- | | 1 | Process Create | | 2 | File Creation Time Changed | | 3 | Network Connection | 5 | Process Terminated | | 7 | Image Loaded | | 8 | CreateRemoteThread | 10 | Process Access | | 11 | File Create | | 12 | Registry Object Create /Delete | | 13 Registry Value Set | | 14 Registry Key/Value Rename | | 16 Sysmon Configuration Change | | 22 | DNS Query | 25 | Process Tampering | The important thing is that not all of these events are necessarily enabled by default The activation of each Event depends on the Sysmon version and Configuration settings. For example, Event ID 3 and 7 are disabled in many configurations to prevent large log volumes. Checking the most important Event, Process Create When a new process is created, Sysmon can record a lot of information about it. For example, suppose the Notepad program is running. The Process Create event may have information like this:
Event ID: 1

Image:
C:\Windows\System32\notepad.exe

ProcessId:
4520

ProcessGuid:
{A1B2-C3D4-E5F6}

CommandLine:
"C:\Windows\System32\notepad.exe"

ParentImage:
C:\Windows\explorer.exe

ParentProcessId:
3100

ParentCommandLine:
C:\Windows\explorer.exe
This information helps us understand: What program Executed? From what path was it executed? What arguments did it have? Which process executed it? What was the parent process? This information is very important for analyzing the behavior of processes What is the difference between Process ID and Process GUID? One of the important points in Sysmon analysis is this Each process has a Process ID or PID But PID can be reassigned to another process after a process is closed For this reason, if we only use PID to relate events, we may make mistakes in the analysis Sysmon also records an identifier called ProcessGuid for each process
17 nov, 02:45

این شناسه برای همبستگی رویدادهای مربوط به یک Process کاربرد داره و مشکل استفاده از PID به‌تنهایی رو تا حد زیادی برطرف میکنه برای مثال:
Process Create

ProcessGuid: {AAAA}
ProcessId: 4520
Image: app.exe
چند لحظه بعد:
Network Connection

ProcessGuid: {AAAA}
ProcessId: 4520
DestinationIp: 192.0.2.10
حالا میتونیم بفهمیم ارتباط شبکه مربوط به همون Process قبلی بوده ساختن یک زنجیره از رفتار Process قدرت اصلی Telemetry وقتی مشخص میشه که چند رویداد رو کنار هم بررسی کنیم فرض کنید یک Process ایجاد شده و بعد فعالیت‌های مختلفی انجام داده
Process Create
Event ID 1
      |
      v
Image Loaded
Event ID 7
      |
      v
DNS Query
Event ID 22
      |
      v
Network Connection
Event ID 3
      |
      v
Process Access
Event ID 10
      |
      v
Process Terminated
Event ID 5
با کنار هم گذاشتن این رویداد ها میتونیم یک دید نسبتا کامل از رفتار Process به دست بیاریم البته این زنجیره به‌تنهایی نشونه بدافزار نیست ممکنه یک برنامه کاملا عادی هم همین رویدادها رو تولید کنه چیزی که اهمیت داره ارتباط بین رویداد ها و زمینه‌ای هست که در اون اتفاق افتادن Sysmon Configuration چیه؟ Sysmon برای اینکه بدونه چه رویداد هایی رو ثبت کنه از یک فایل Configuration استفاده میکنه این فایل معمولا با فرمت XML نوشته میشه داخل Configuration مشخص میکنیم: کدوم Eventها ثبت بشن چه Processهایی شامل مانیتورینگ بشن چه مسیرهایی بررسی بشن چه رویدادهایی از ثبت شدن مستثنا بشن برای مثال ممکنه بخوایم فقط فعالیت مربوط به تعدادی از Process های مشخص رو ثبت کنیم اینجا از Include و Exclude Filter استفاده میشه نکته مهم اینه که اگر Configuration بیش از حد محدود باشه ممکنه رویداد های مهمی رو از دست بدیم از طرف دیگه اگر همه‌چیز رو بدون فیلتر ثبت کنیم حجم زیادی از لاگ تولید میشه و تحلیل اون سخت‌تر میشه پس طراحی Configuration خودش بخشی از کار Detection Engineering محسوب میشه تمرین: برای اینکه این مفاهیم رو بهتر درک کنید روی یک ماشین آزمایشگاهی این مراحل رو انجام بدید. مرحله اول Sysmon رو از منبع رسمی Microsoft Sysinternals دریافت کنید: [Microsoft Sysmon Documentation](https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon?utm_source=chatgpt.com) مرحله دوم Sysmon رو با یک Configuration معتبر و پایه روی ماشین آزمایشگاهی نصب کنید مرحله سوم برنامه Notepad رو اجرا کنید مرحله چهارم وارد Event Viewer بشید و مسیر زیر رو باز کنید:
Applications and Services Logs
    |
    └── Microsoft
         |
         └── Windows
              |
              └── Sysmon
                   |
                   └── Operational
مرحله پنجم رویداد Event ID 1 رو پیدا کنید و این فیلدها رو بررسی کنید:
Image
ProcessId
ProcessGuid
CommandLine
ParentImage
ParentProcessId
ParentCommandLine
حالا Notepad رو ببندید و بررسی کنید که Event ID 5 هم ثبت شده یا نه اگر Event ID های مربوط به DNS و Network Connection در Configuration فعال باشن میتونید اون‌ها رو هم بررسی کنید محدودیت‌های Sysmon Sysmon ابزار قدرتمندیه اما محدودیت‌هایی هم داره: همه فعالیت‌های سیستم رو ثبت نمیکنه بعضی Event ها به تنظیمات نیاز دارن حجم زیاد لاگ میتونه تحلیل رو دشوار کنه بعضی رویدادها ممکنه در نرم‌ افزارهای عادی هم دیده بشن ثبت شدن یک Event به‌ تنهایی ثابت نمیکنه فعالیت مخرب بوده پس در تحلیل امنیتی نباید فقط به یک Event ID تکیه کنیم باید رفتار Process والد اون Command Line زمان اجرا و رویداد های مرتبط رو در کنار هم بررسی کنیم @reverseengine
17 nov, 02:39

Sysmon و Process Telemetry تا اینجا با ETW آشنا شدیم و دیدیم ویندوز چطور رویداد های مختلف سیستم رو ثبت و در اختیار ابزارهای مانیتورینگ قرار میده حالا میخوایم بریم سراغ یکی از ابزارهای مهم در تحلیل رفتار Processها یعنی Sysmon Sysmon کمک میکنه بفهمیم داخل سیستم چه اتفاقاتی افتاده و Processها چه فعالیت‌هایی انجام دادن Sysmon Sysmon یا System Monitor یکی از ابزارهای مجموعه Microsoft Sysinternals هست که فعالیت‌های مختلف سیستم رو مانیتور میکنه و اطلاعات مربوط به اون‌ها رو داخل Windows Event Log ثبت میکنه برای مثال میتونه اطلاعاتی درباره این موارد ثبت کنه: ایجاد و خاتمه Process ها ایجاد Process فرزند اپلود DLL و Image ها ارتباطات شبکه دسترسی یک Process به Process دیگه تغییرات Registry ایجاد فایل درخواست‌ های DNS یه نکته مهم: Sysmon خودش یک EDR یا موتور تشخیص بدافزار نیست وظیفه اصلیش جمع کردن و ثبت Telemetry هست ابزارهای امنیتی میتونن از این اطلاعات برای تحلیل رفتار سیستم و شناسایی فعالیت‌های مشکوک استفاده کنن تفاوت ETW و Event Log و Sysmon این سه مفهوم به هم مرتبطن ولی یک معنی ندارن مسیر مشاهده رویدادهای Sysmon:
Event Viewer
    |
    └── Applications and Services Logs
             |
             └── Microsoft
                  |
                  └── Windows
                       |
                       └── Sysmon
                            |
                            └── Operational
آشنایی با Event ID های مهم هر رویدادی که Sysmon ثبت میکنه یک Event ID مشخص داره چند مورد مهم: | Event ID | رویداد | | -------- | ----------------------------- | | 1 | Process Create | | 2 | File Creation Time Changed | | 3 | Network Connection | | 5 | Process Terminated | | 7 | Image Loaded | | 8 | CreateRemoteThread | | 10 | Process Access | | 11 | File Create | | 12 | Registry Object Create /Delete | | 13 | Registry Value Set | | 14 | Registry Key/Value Rename | | 16 | Sysmon Configuration Change | | 22 | DNS Query | | 25 | Process Tampering | نکته مهم اینه که همه این رویداد ها حتما به‌صورت پیش‌فرض فعال نیستن فعال بودن هر Event به نسخه Sysmon و تنظیمات Configuration بستگی داره مثلا Event ID 3 و 7 در بسیاری از پیکربندی‌ ها برای جلوگیری از تولید حجم زیاد لاگ غیرفعال هستن بررسی مهم‌ ترین Event یعنی Process Create وقتی یک Process جدید ایجاد میشه Sysmon میتونه اطلاعات زیادی درباره اون ثبت کنه برای مثال فرض کنید برنامه Notepad اجرا شده رویداد Process Create ممکنه اطلاعاتی شبیه این داشته باشه:
Event ID: 1

Image:
C:\Windows\System32\notepad.exe

ProcessId:
4520

ProcessGuid:
{A1B2-C3D4-E5F6}

CommandLine:
"C:\Windows\System32\notepad.exe"

ParentImage:
C:\Windows\explorer.exe

ParentProcessId:
3100

ParentCommandLine:
C:\Windows\explorer.exe
این اطلاعات بهمون کمک میکنن بفهمیم: چه برنامه‌ای اجرا شده؟ از چه مسیری اجرا شده؟ چه آرگومان‌هایی داشته؟ کدوم Process اون رو اجرا کرده؟ Process والد چی بوده؟ این اطلاعات برای تحلیل رفتار Process ها اهمیت زیادی دارن Process ID و Process GUID چه تفاوتی دارن؟ یکی از نکات مهم در تحلیل Sysmon همین موضوعه هر Process یک Process ID یا PID داره اما PID میتونه بعد از بسته شدن یک Process دوباره به Process دیگه‌ای اختصاص داده بشه به همین دلیل اگر فقط PID رو برای ارتباط دادن رویدادها استفاده کنیم ممکنه در تحلیل دچار اشتباه بشیم Sysmon برای هر Process یک شناسه به نام ProcessGuid هم ثبت میکنه
17 nov, 02:39

for address in callers: function = project.kb.functions[address] print(function.name) This method is very useful for analyzing the behavior of important functions For example, if a function is responsible for checking user input, we can check what functions call it and from what paths it can be accessed Finding functions that a function calls Now let's examine the opposite case We want to see what functions the process_request function calls directly python target = project.kb.functions["process_request"] callees = call_graph.successors( target.addr ) for address in callees: function = project.kb.functions[address] print(function.name) Here we used successors That is, the Nodes that have an Edge from the desired function to them In this way, we can check the direct connection between functions Difference between Caller and Callee These two terms are very used in code analysis They are Caller A function that calls another function Callee A function that is called by another function For example, the following line of code c authenticate(); The function that contains this statement is considered the Caller, and authenticate plays the role of Callee This simple difference is very important in Call Graph analysis Limitations of Call Graph Call Graph is not always a complete picture of the relationship between functions Several things can reduce its accuracy Indirect Calls Sometimes the address of the target function is not specified directly in the calling statement For example, inside a call via Function Pointer c void (*handler)(void) = log_event; handler(); In this situation, we need to identify the actual destination of the call Dynamic Linking Some functions are made available at runtime through shared libraries If the libraries are not uploaded in the analysis, the information related to some calls may not be complete Stripped Binaries If the symbol information is removed from the executable file, the actual name of the functions may not be known In this situation, it is still possible to check the connections with the function addresses, but it becomes more difficult to understand the role of each function Virtual Calls In object-oriented programs, calling functions through Virtual Tables can complicate the identification of the exact destination Its application Suppose we have an anonymous executable file and we want to examine the behavior of a specific function With Call Graph, we can approach the analysis from two directions Check from top to bottom what functions reach the desired function Check from bottom to top what functions the desired function calls This helps Understand the dependencies of a function better and narrow the scope of analysis In this section, we learned how the Call Graph displays the relationship between functions and how we can extract this graph with angr And we got acquainted with the concept of Caller and Callee and the method of examining callers and called functions An important technical point: In the angr code, using project.kb.functions[address] to access the function by address is appropriate, but in different versions and conditions, some function nodes may not be identifiable, and also predecessors show the number of distinct calling functions, not the number of times the function is executed @reverseengine
17 nov, 02:06

target = project.kb.functions["authenticate"]

callers =   call_graph.predecessors(
      target.addr
  )
17 nov, 02:04

Part 40 Buffer Overflow Call Graph Analysis with angr In the previous part, we learned how to use CFG to examine the control flow structure of a program and obtain the relationship between Basic Blocks But there is a more important question When we are faced with a large executable file, how do we understand how different functions of the program are related to each other? For example, which function calls another function? Which functions are accessible from several different parts of the program? And if we want to examine the behavior of a suspicious function, how do we understand which parts of the program call it? To answer these questions, we use a concept called Call Graph. Call Graph Call Graph is a directed graph that shows the call relationships between program functions. In this graph, Each Node represents a function. Each Edge represents a call relationship from one function to another. For example, suppose we have a program with the following structure: #include <stdio.h> void log_event(void) { puts("Event logged"); } void authenticate(void) { log_event(); puts("Authentication"); } void process_request(void) { authenticate(); puts("Request processed"); } int main(void) { process_request(); return 0; } In this program, the main function calls the process_request function The process_request function also calls authenticate Finally, authenticate executes the log_event function The Call Graph structure is as follows main | v process_request | v authenticate | v log_event By looking at this graph, we can follow the path of function calls Building a Call Graph with angr To start, save the above program in a file called callgraph.c and compile it gcc -O0 -fno-pie -no-pie callgraph.c -o callgraph Now create the following script called callgraph.py import angr project = angr.Project( "./callgraph", auto_load_libs=False ) cfg = project.analyses.CFGFast() call_graph = cfg.kb.functions.callgraph print("Nodes:", len(call_graph.nodes)) print("Edges:", len(call_graph.edges)) Here, first we extract the program control flow structure with CFGFast Then, using the information that angr has obtained about the functions, we get the Call Graph The important point is that the Call Graph is derived from the CFG analysis information It is created and therefore its accuracy depends on the quality of the initial analysis Showing the relationship between functions Now we want to see which function calls which other function for source, destination in call_graph.edges(): source_func = project.kb.functions[source] destination_func = project.kb.functions[destination] print( source_func.name, "->", destination_func.name ) The expected output for the main functions of the program is approximately like this main -> process_request process_request -> authenticate authenticate -> log_event In addition, it is possible that the relationships related to library functions or other internal functions can also be seen in the output Because the way to identify functions and calls depends on the version of angr and the structure of the executable file Finding functions that have the most callers One of the uses of Call Graph is finding functions that are called from different parts of the program For This allows us to check the number of incoming callers for each function for address in call_graph.nodes: function = project.kb.functions[address] callers = list( call_graph.predecessors(address) ) print( function.name, "Callers:", len(callers) ) Here we used predecessors In a directed graph, the predecessors of a node are the nodes that have an edge towards it So in the Call Graph, these are the functions that call the function in question Of course, the number of predecessors is not necessarily the number of times the function is executed A function may be executed many times from a specific location but still have only one caller in the graph Finding functions that call a specific function Suppose we have a function called authenticate and we want to know which parts of the program call it
17 nov, 02:04

for address in callers:
    function = project.kb.functions[address]
    print(function.name)
این روش برای تحلیل رفتار توابع مهم کاربرد زیادی داره مثلا اگر تابعی وظیفه بررسی ورودی کاربر رو برعهده داشته باشه میتونیم بررسی کنیم چه توابعی اون رو فراخوانی میکنن و از چه مسیرهایی قابل دسترسیه پیدا کردن توابعی که یک تابع فراخوانی میکنه حالا حالت برعکس رو بررسی کنیم میخوایم ببینیم تابع process_request چه توابعی رو مستقیما فراخوانی میکنه
python
target = project.kb.functions["process_request"]

callees = call_graph.successors(
    target.addr
)

for address in callees:
    function = project.kb.functions[address]
    print(function.name)
اینجا از successors استفاده کردیم یعنی Node هایی که از تابع موردنظر یک Edge به سمت اون‌ها وجود داره به این ترتیب میتونیم ارتباط مستقیم بین توابع رو بررسی کنیم تفاوت Caller و Callee این دو اصطلاح در تحلیل کد خیلی استفاده میشن Caller تابعی که تابع دیگه‌ ای رو فراخوانی میکنه Callee تابعی که توسط یک تابع دیگه فراخوانی میشه برای مثال یک خط کد زیر
c

authenticate();
تابعی که این دستور داخل اون قرار داره Caller محسوب میشه و authenticate نقش Callee رو داره این تفاوت ساده در تحلیل Call Graph اهمیت زیادی داره محدودیت‌های Call Graph Call Graph همیشه تصویر کاملی از ارتباط بین توابع نیست چند مورد میتونن دقت اون رو کم کنن Indirect Calls بعضی وقتا آدرس تابع مقصد مستقیما داخل دستور فراخوانی مشخص نیست مثلا داخل فراخوانی از طریق Function Pointer c void (*handler)(void) = log_event; handler(); در این شرایط ما باید مقصد واقعی فراخوانی رو تشخیص بدیم Dynamic Linking بعضی توابع از طریق کتابخونه‌ های اشتراکی در زمان اجرا در دسترس قرار می‌ گیرن اگر کتابخونه‌ ها در تحلیل اپلود نشده باشن ممکنه اطلاعات مربوط به بعضی فراخوانی‌ ها کامل نباشه Stripped Binaries اگر اطلاعات Symbol ها از فایل اجرایی حذف شده باشن ممکنه اسم واقعی توابع مشخص نباشه در این شرایط بازم میشه ارتباط‌ ها رو با آدرس توابع بررسی کرد اما فهمیدن نقش هر تابع سخت‌تر میشه Virtual Calls در برنامه‌ های شی‌گرا فراخوانی توابع از طریق Virtual Table میتونه تشخیص مقصد دقیق رو پیچیده‌تر کنه کاربردش فرض کنید یک فایل اجرایی ناشناس در اختیار داریم و میخوایم رفتار یک تابع مشخص رو بررسی کنیم با Call Graph میتونیم از دو جهت به تحلیل نزدیک بشیم از بالا به پایین بررسی کنیم چه توابعی به تابع موردنظر میرسن از پایین به بالا بررسی کنیم تابع مورد نظر چه توابعی رو فراخوانی میکنه این کار کمک میکنه وابستگی‌ های یک تابع رو بهتر بشناسیم و محدوده تحلیل رو کوچک‌تر کنیم در این قسمت یاد گرفتیم Call Graph چطور ارتباط بین توابع رو نمایش میده و چطور با angr میتونیم این گراف رو استخراج کنیم و با مفهوم Caller و Callee و روش بررسی فراخوانی‌ کننده‌ها و توابع فراخوانی‌شده آشنا شدیم یک نکته فنی مهم: در کد angr استفاده از project.kb.functions[address] برای دسترسی به تابع با آدرس مناسبه اما در نسخه‌ ها و شرایط مختلف ممکنه بعضی Node های تابع قابل‌ شناسایی نباشه و همچنین predecessors تعداد تابع‌ های فراخوانی‌ کننده متمایز رو نشون بده نه تعداد دفعات اجرای تابع @reverseengine
17 nov, 01:59

بخش چهلم بافر اورفلو
Call Graph Analysis با angr در قسمت قبل یاد گرفتیم چطور با استفاده از CFG ساختار جریان کنترل برنامه رو بررسی کنیم و ارتباط بین Basic Blockها رو به دست بیاریم اما یک سوال مهم‌تر وجود داره وقتی با یک فایل اجرایی بزرگ رو به‌ رو هستیم چطور بفهمیم توابع مختلف برنامه چه ارتباطی با هم دارن؟ مثلا کدوم تابع، تابع دیگه‌ ای رو صدا میزنه؟ کدوم توابع از چند بخش مختلف برنامه قابل دسترسی هستن؟ و اگر بخوایم رفتار یک تابع مشکوک رو بررسی کنیم چطور بفهمیم چه بخش‌ هایی از برنامه اون رو فراخوانی میکنن؟ برای جواب دادن به این سوال‌ها از مفهومی به اسم Call Graph استفاده میکنیم Call Graph Call Graph یک گراف جهت‌ داره که ارتباط فراخوانی بین توابع برنامه رو نمایش میده در این گراف هر Node نماینده یک تابع هست هر Edge نشون‌دهنده یک ارتباط فراخوانی از یک تابع به تابع دیگه است برای مثال فرض کنید برنامه‌ای با ساختار زیر داریم:
#include <stdio.h>

void log_event(void)
{
    puts("Event logged");
}

void authenticate(void)
{
    log_event();
    puts("Authentication");
}

void process_request(void)
{
    authenticate();
    puts("Request processed");
}

int main(void)
{
    process_request();
    return 0;
}
در این برنامه تابع main تابع process_request رو صدا میزنه تابع process_request هم authenticate رو فراخوانی میکنه در اخر authenticate تابع log_event رو اجرا میکنه ساختار Call Graph به این شکله
main
  |
  v
process_request
  |
  v
authenticate
  |
  v
log_event
با نگاه به این گراف میتونیم مسیر فراخوانی توابع رو دنبال کنیم ساخت Call Graph با angr برای شروع برنامه بالا رو داخل فایلی به اسم callgraph.c ذخیره کنید و کامپایلش کنید
gcc -O0 -fno-pie -no-pie callgraph.c -o callgraph
حالا اسکریپت زیر رو با اسم callgraph.py بسازید
import angr

project = angr.Project(
    "./callgraph",
    auto_load_libs=False
)

cfg = project.analyses.CFGFast()

call_graph = cfg.kb.functions.callgraph

print("Nodes:", len(call_graph.nodes))
print("Edges:", len(call_graph.edges))
در اینجا اول با CFGFast ساختار جریان کنترل برنامه رو استخراج میکنیم بعد از اون با استفاده از اطلاعاتی که angr درباره توابع به دست اورده Call Graph رو میگیریم نکته مهم اینه که Call Graph از اطلاعات تحلیل CFG ساخته میشه و به همین دلیل دقت اون به کیفیت تحلیل اولیه وابسته است نمایش ارتباط بین توابع حالا میخوایم ببینیم چه تابعی کدوم تابع دیگه رو فراخوانی میکنه
for source, destination in call_graph.edges():
    source_func = project.kb.functions[source]
    destination_func = project.kb.functions[destination]

    print(
        source_func.name,
        "->",
        destination_func.name
    )
خروجی مورد انتظار برای توابع اصلی برنامه تقریبا به این شکله
main -> process_request
process_request -> authenticate
authenticate -> log_event
ممکنه علاوه بر اینها ارتباط‌ های مربوط به توابع کتابخانه‌ای یا توابع داخلی دیگه هم در خروجی دیده بشن چون نحوه شناسایی توابع و فراخوانی‌ها به نسخه angr و ساختار فایل اجرایی وابسته است پیدا کردن توابعی که بیشترین فراخوانی‌کننده رو دارن یکی از کاربردهای Call Graph پیدا کردن توابعیه که از بخش‌های مختلف برنامه فراخوانی میشن برای این کار میتونیم تعداد فراخوانی‌کننده‌ های ورودی هر تابع رو بررسی کنیم
for address in call_graph.nodes:
    function = project.kb.functions[address]

    callers = list(
        call_graph.predecessors(address)
    )

    print(
        function.name,
        "Callers:",
        len(callers)
    )
اینجا از predecessors استفاده کردیم در یک گراف جهت‌دار predecessor های یک Node همون Node هایی هستن که یک Edge به سمت اون دارن پس در Call Graph اینها توابعی هستن که تابع موردنظر رو فراخوانی میکنن البته تعداد predecessorها لزوما تعداد دفعات اجرای تابع نیست ممکنه یک تابع از یک محل مشخص بارها اجرا بشه اما بازم فقط یک فراخوانی‌ کننده در گراف داشته باشه پیدا کردن توابعی که یک تابع خاص رو فراخوانی میکنن فرض کنید تابعی به اسم authenticate داریم و میخوایم بدونیم چه بخش‌هایی از برنامه اون رو صدا میزنن `python target = project.kb.functions["authenticate"] callers = call_graph.predecessors( target.addr )
17 nov, 01:59

Reduced average turnaround time Important limitations Need to estimate the job execution time Problem with different entry times Possibility of Starvation and Remember SJF = Non-preemptive @reverseengine
17 nov, 01:23

Shortest Job First (SJF) In the previous section, we saw that FIFO can cause a problem called Convoy Effect That is, a long job is placed in front of several short jobs and they all have to wait Now suppose we can know the execution time of each job In this case, we can sort the jobs based on their execution time instead of the order of entry This is where the Shortest Job First algorithm comes in The main idea of ​​SJF The SJF rule is simple Among the jobs that are ready to run, the job with the shortest CPU execution time is selected first For example: A = 24ms B = 3ms C = 3ms If all jobs are entered into the system at the same time, the execution order will be as follows B → C → A Timeline 0 3 6 30 |----|----|-------------------| B C A Compared to FIFO, short jobs execute much faster Calculating Turnaround Time Consider the same previous jobs Since all arrived at time zero Turnaround = Completion - Arrival Then A = 30ms B = 3ms C = 6ms Average (30 + 3 + 6) / 3 = 13ms Now compare with FIFO FIFO Average Turnaround = 27ms SJF Average Turnaround = 13ms In this example, SJF significantly reduced the average turnaround time Why is SJF theoretically important? If all jobs enter the system at the same time and we know their execution time in advance, executing the shorter jobs first can minimize the average turnaround time This is one of the important features of SJF But there is a big problem How does the operating system know how long the job will take? Suppose a Process enters the system The operating system usually cannot know with certainty whether this Process 2ms of CPU time or 200ms It is even possible that the behavior of the program depends on the user input For example: CPU Burst ↓ I/O Wait ↓ CPU Burst ↓ I/O Wait ↓ CPU Burst So the execution time of a program is not necessarily a fixed and predetermined number That is why SJF in its ideal form has limitations for real operating systems When Jobs enter at different times Suppose we have three Jobs A: Arrival = 0 Runtime = 10 B: Arrival = 1 Runtime = 2 C: Arrival = 2 Runtime = 1 At time zero, only A is ready to run So SJF is forced to run A When B and C enter, A is still running In a normal SJF, the execution of A does not stop and the execution order is as follows 0 10 12 13 |---------------|----|---| A B C The important point is that the normal SJF is Non-preemptive That is, when a Job starts executing, it will not be taken over by a shorter Job Non-preemptive In Scheduling, we have two important behaviors Non-preemptive Once a Job is executed, it will continue until the end of the CPU Burst unless it stops itself or waits for I/O Preemptive Scheduler Can stop the execution of the current Job and give the CPU to another Job In normal SJF, the decision is made when selecting the Job and the running Job does not stop due to the entry of a shorter Job Relationship of SJF with Starvation There is another possible problem Suppose a long Job is waiting in the queue But new short Jobs are constantly entering The Scheduler Always selects the shorter Job As a result, the long Job may wait for a very long time We call this situation Starvation That is, a Job does not get a suitable opportunity to execute due to the scheduling policy Of course, it happens It depends on the system conditions and the scheduler policy In analyzing real applications, CPU and I/O behavior is very important Suppose a program has multiple threads Process ├── Thread A │ └── CPU-heavy work │ ├── Thread B │ └── Short operation │ └── Thread C └── I/O operation If the threads have different behaviors, the way they are scheduled affects their response time and the order in which the program is executed This issue becomes important when considering the following: Timing Behavior Thread Synchronization Race Condition Performance Bottlenecks Deadlock Analysis So Scheduling is not just a theoretical issue and part of the real program behavior depends on the scheduler's decisions SJF is an algorithm that selects the shortest job from the ready jobs Main advantage
17 nov, 01:23

Utilizamos cookies para mejorar tu experiencia de navegación.
Al hacer clic en «Aceptar todo», aceptas la política de uso de cookies.