# Exercises - patching

## Task 1

You are given a snippet in assembly: 

+ [patching1.asm](../task1/patching1.asm)

Compile it using MASM. Check how it works.

1. To compile use:
```
ml patching1.asm
```

or:

```
ml \c patching1.asm
link patching1.obj
```

+ Why you don't have to supply any libraries to the linker this time?
>Answer: because all the libraries needed are now listed in the assembly file

```asm
; added:
INCLUDELIB USER32.lib
INCLUDELIB KERNEL32.lib
INCLUDELIB ADVAPI32.lib
```

+ You task is to patch the assembly file in such a way that it will give you the flag. Any working patch is allowed, but try to make it as simple as possible.
> Sample solution: [task1/patching1_sol.asm](task1/patching1_sol.asm)

## Task 2

You are given a compiled application:

+ [expired_flag.exe](../task2/expired_flag.exe)

1. Open the exe in IDA and analyze what is happening there, what conditions are checked, etc.

2. Using a debugger of your choice (x64dbg is recommended) change the checked flags, to bypass the checked conditions, and bypass the "Expired" MessageBox

3. Try to achieve the same goal like 2, but without touching the flags registers, but the actual values that are filled by the relevant function call. Keep trying various bypasses until you get the flag pop up.

4. Write a x64dbg script that will repeat the steps that you have done in a debugger in order to obtain the flag pop up.
> //TODO

5. Make patches in the compiled application to make it always display the flag.

> Answer: Remove the fragment of code responsible for making checks, and replace it with the code that fills relevant variables with expected values. Proposed patch:
```asm
mov edx,7E3 
mov [ebp-0x48], dx
mov eax,5
mov [ebp-0x46], ax 
```
> Nop-out the code that is not needed, to make the space for the patch.

+ notice that x64dbg may alert you about relocations affecting your patches. 

Q1: What does it mean?
> Details of the PE relocation process will be explained in the next lesson. For now you just need to remember that relocations cause some modifications to be applied on the code at the moment when the PE is loaded. If the relocations collide with your patches, the code that you overwritten will be destroyed.

Q2: How can you solve this problem?
>Answer: by disabling the flag "DLL can move" in the PE header. This will disable relocations (PE will have a static base).

> Sample solution: [task2/expired_flag_sol.exe](task2/expired_flag_sol.exe)

6. What are the other ideas for patching that could be applied in such case?
> Answer: hooking of the function `GetLocalTime` and making it return always the expected value.
