Chapter 4: Operator CLI Client
Creating a CLI client to interact with the listening post and implant.
building-c2-implants-in-cpp-master.zip
230KB
Binary
Book Source Code

Introduction

In this chapter, we'll be building out our operator CLI client called Fireworks. The CLI client will allow us to interact with our listening post via the REST API and serve as an easy way for operators to submit new taskings/view results in a command prompt. The actions will include:
  • list-tasks
    • Lists the tasks that are being served to the implant
  • add-tasks --tasktype <task_type> --options <key>=<value>
    • Submit tasks to the listening post
  • list-results
    • List the results returned from the implant
  • list-history
    • List the history of tasks and their associated results
The reason why we're building a CLI and not a web interface is mainly for reasons of rapid testing and experimentation. I would personally prefer to begin with an interface that's easy to build and test with before I start putting in the time to build out a web interface that may end up being more complicated. When we're confident that our C2 is functioning well with the CLI and we're satisfied with the various core user flows, then we can take the steps towards building a web interface with something like Vue.js or Bootstrap.
Okay, let's get started! Open the folder called "chapter4-1" and you'll find the following code in the file fireworks.py. Install the requirements by running pip install -r requirements.txt to ensure you have all the prerequisites installed. We'll start by going through each code block and try to understand how the CLI client is working:
fireworks.py
1
import click
2
import requests
3
import pprint
4
import json
5
6
# Configuration Settings
7
listening_post_addr = "http://127.0.0.1:5000"
8
9
# Helper functions
10
def api_get_request(endpoint):
11
response_raw = requests.get(listening_post_addr + endpoint).text
12
response_json = json.loads(response_raw)
13
return response_json
14
15
# CLI commands and logic
16
@click.group()
17
def cli():
18
pass
19
20
@click.command(name="list-tasks")
21
def list_tasks():
22
"""Lists the tasks that are being served to the implant."""
23
api_endpoint = "/tasks"
24
print("\nHere's the tasks:\n")
25
pprint.pprint(api_get_request(api_endpoint))
26
print()
27
28
@click.command(name="list-results")
29
def list_results():
30
"""List the results returned from the implant."""
31
api_endpoint = "/results"
32
print("\nHere's the results:\n")
33
pprint.pprint(api_get_request(api_endpoint))
34
print()
35
36
@click.command(name="list-history")
37
def list_history():
38
"""List the history of tasks and their associated results."""
39
api_endpoint = "/history"
40
print("\nHere's the tasks history:\n")
41
pprint.pprint(api_get_request(api_endpoint))
42
print()
43
44
# Add commands to CLI
45
cli.add_command(list_tasks)
46
cli.add_command(list_results)
47
cli.add_command(list_history)
48
49
if __name__ == '__main__':
50
cli()
Copied!

Boilerplate

First, let's get some of the boilerplate out of the way with the following block:
1
# Configuration Settings
2
listening_post_addr = "http://127.0.0.1:5000"
3
4
# Helper functions
5
def api_get_request(endpoint):
6
response_raw = requests.get(listening_post_addr + endpoint).text
7
response_json = json.loads(response_raw)
8
return response_json
9
10
# CLI commands and logic
11
@click.group()
12
def cli():
13
pass
Copied!
We set a variable that holds the address of our listening post and we declare a function for making an HTTP GET request to our API endpoints. The "api_get_request" function accepts the API endpoint as an argument and uses it to make a GET request using the Python Requests library. It stores the response from the listening post in a variable called "response_raw". Then, we parse the result as a JSON object and store it into "response_json". This is what we will return to the user. We then start our section for CLI commands and logic. We're using the Python Click library to build our CLI client and the "@click.group()" syntax is used to group together commands. We then declare a "cli" function that will simply pass and allow us to execute various commands based on the input provided by the user.

CLI List Commands

In the following code block, we define each of the implant "list" commands that consist of a simple GET request to the listening post:
1
@click.command(name="list-tasks")
2
def list_tasks():
3
"""Lists the tasks that are being served to the implant."""
4
api_endpoint = "/tasks"
5
print("\nHere's the tasks:\n")
6
pprint.pprint(api_get_request(api_endpoint))
7
print()
8
9
@click.command(name="list-results")
10
def list_results():
11
"""List the results returned from the implant."""
12
api_endpoint = "/results"
13
print("\nHere's the results:\n")
14
pprint.pprint(api_get_request(api_endpoint))
15
print()
16
17
@click.command(name="list-history")
18
def list_history():
19
"""List the history of tasks and their associated results."""
20
api_endpoint = "/history"
21
print("\nHere's the tasks history:\n")
22
pprint.pprint(api_get_request(api_endpoint))
23
print()
Copied!
The overall format of each list command is roughly the same. We specify the name of the command that the user will type on the command line with @click.command(name="list-tasks") and then start writing the function code for that command. We write out some help text that will be displayed for the command if the user types "--help" and declare what the API endpoint is. Lastly, we pretty print out the results of calling the List API with a GET request.
To close out this initial CLI client, we need to add the following.
1
# Add commands to CLI
2
cli.add_command(list_tasks)
3
cli.add_command(list_results)
4
cli.add_command(list_history)
5
6
if __name__ == '__main__':
7
cli()
Copied!
The above code block adds the list commands to the CLI and we then specify the main function. That's all we need to start testing out the CLI client, let's get ready for a test drive.

List Commands Test Drive

Let's try out this client now by starting up the listening post. You can navigate to the "Skytree" folder to find the listening_post.py file and then run the command python listening_post.py. When that's running, start the implant. You can navigate to the "RainDoll" folder and use the Visual Studio solution file to build a new RainDoll.exe binary or you can run a binary from an earlier chapter. With both the listening post and the implant running, we're ready to run a list command with the CLI client using the following:
1
python fireworks.py list-tasks
Copied!
You should see the following response:
1
Here's the tasks:
2
3
[]
Copied!
You can get help for each of the commands that are supported with:
1
python fireworks.py --help
Copied!
You'll get back:
1
Usage: fireworks.py [OPTIONS] COMMAND [ARGS]...
2
3
Options:
4
--help Show this message and exit.
5
6
Commands:
7
list-history List the history of tasks and their associated results.
8
list-results List the results returned from the implant.
9
list-tasks Lists the tasks that are being served to the implant.
Copied!
You can run any of the list commands and you should get back a 200 OK from the listening post. So far, this CLI client isn't terribly useful. But, at least we know it's able to successfully make requests to the listening post API and get back responses. Let's add a mutating command that's a bit more complicated by implementing the Add Tasks command.

CLI Add Tasks Command

Open the folder called "chapter4-2" and you'll find the following updated code in the file fireworks.py. We'll go through each code block and try to understand how the Add Tasks command is working:
fireworks.py
1
import click
2
import requests
3
import pprint
4
import json
5
6
# Configuration Settings
7
listening_post_addr = "http://127.0.0.1:5000"
8
9
# Helper functions
10
def api_get_request(endpoint):
11
response_raw = requests.get(listening_post_addr + endpoint).text
12
response_json = json.loads(response_raw)
13
return response_json
14
15
def api_post_request(endpoint, payload):
16
response_raw = requests.post(listening_post_addr + endpoint, json=payload).text
17
response_json = json.loads(response_raw)
18
return response_json
19
20
# CLI commands and logic
21
@click.group()
22
def cli():
23
pass
24
25
@click.command(name="list-tasks")
26
def list_tasks():
27
"""Lists the tasks that are being served to the implant."""
28
api_endpoint = "/tasks"
29
print("\nHere's the tasks:\n")
30
pprint.pprint(api_get_request(api_endpoint))
31
print()
32
33
@click.command(name="list-results")
34
def list_results():
35
"""List the results returned from the implant."""
36
api_endpoint = "/results"
37
print("\nHere's the results:\n")
38
pprint.pprint(api_get_request(api_endpoint))
39
print()
40
41
@click.command(name="list-history")
42
def list_history():
43
"""List the history of tasks and their associated results."""
44
api_endpoint = "/history"
45
print("\nHere's the tasks history:\n")
46
pprint.pprint(api_get_request(api_endpoint))
47
print()
48
49
@click.command(name="add-tasks")
50
@click.option('--tasktype', help='Type of task to submit.')
51
@click.option('--options', help='Key-value options for task.')
52
def add_tasks(tasktype, options):
53
"""Submit tasks to the listening post."""
54
api_endpoint = "/tasks"
55
print("\nHere are the tasks that were added:\n")
56
57
# Perform options parsing if user provided them to the task
58
if options != None:
59
task_options_dict = {}
60
task_options_pairs = options.split(",")
61
62
# For each key-value pair, add them to a dictionary
63
for option in task_options_pairs:
64
key_vals = option.split("=")
65
key = key_vals[0]
66
value = key_vals[1]
67
pair = {key:value}
68
task_options_dict.update(pair)
69
70
# If more than one option was provided, format and append them into a single string
71
if len(task_options_dict) > 1:
72
keyval_string = ""
73
for key,value in task_options_dict.items():
74
keyval_string += f'"{key}":"{value}",'
75
request_payload_string = f'[{{"task_type":"{tasktype}",{keyval_string[:-1]}}}]'
76
request_payload = json.loads(request_payload_string)
77
pprint.pprint(api_post_request(api_endpoint, request_payload))
78
# Otherwise, just print the key/value for the single option provided
79
else:
80
request_payload_string = f'[{{"task_type":"{tasktype}","{key}":"{value}"}}]'
81
request_payload = json.loads(request_payload_string)
82
pprint.pprint(api_post_request(api_endpoint, request_payload))
83
# Otherwise, we just submit a payload with the task type specified
84
else:
85
request_payload_string = f'[{{"task_type":"{tasktype}"}}]'
86
request_payload = json.loads(request_payload_string)
87
pprint.pprint(api_post_request(api_endpoint, request_payload))
88
print()
89
90
# Add commands to CLI
91
cli.add_command(list_tasks)
92
cli.add_command(list_results)
93
cli.add_command(list_history)
94
cli.add_command(add_tasks)
95
96
if __name__ == '__main__':
97
cli()
98
Copied!
For the Add Tasks command, we need to be able to make POST requests to the listening post:
1
def api_post_request(endpoint, payload):
2
response_raw = requests.post(listening_post_addr + endpoint, json=payload).text
3
response_json = json.loads(response_raw)
4
return response_json
Copied!
In the above code block, we define another helper function that uses the Python Requests library to make the POST request. It accepts an "endpoint" parameter and a new "payload" parameter that will hold our JSON request body. In the "requests.post" method, we specify the "json" parameter as containing our payload. Next, we parse the response from the listening post as JSON and return this to the user.
Now, we're ready to go over the Add Tasks command and the way that we build the POST request body:
1
@click.command(name="add-tasks")
2
@click.option('--tasktype', help='Type of task to submit.')
3
@click.option('--options', help='Key-value options for task.')
4
def add_tasks(tasktype, options):
5
"""Submit tasks to the listening post."""
6
api_endpoint = "/tasks"
7
print("\nHere are the tasks that were added:\n")
8
9
# Perform options parsing if user provided them to the task
10
if options != None:
11
task_options_dict = {}
12
task_options_pairs = options.split(",")
13
14
# For each key-value pair, add them to a dictionary
15
for option in task_options_pairs:
16
key_vals = option.split("=")
17
key = key_vals[0]
18
value = key_vals[1]
19
pair = {key:value}
20
task_options_dict.update(pair)
21
22
# If more than one option was provided, format and append them into a single string
23
if len(task_options_dict) > 1:
24
keyval_string = ""
25
for key,value in task_options_dict.items():
26
keyval_string += f'"{key}":"{value}",'
27
request_payload_string = f'[{{"task_type":"{tasktype}",{keyval_string[:-1]}}}]'
28
request_payload = json.loads(request_payload_string)
29
pprint.pprint(api_post_request(api_endpoint, request_payload))
30
# Otherwise, just print the key/value for the single option provided
31
else:
32
request_payload_string = f'[{{"task_type":"{tasktype}","{key}":"{value}"}}]'
33
request_payload = json.loads(request_payload_string)
34
pprint.pprint(api_post_request(api_endpoint, request_payload))
35
# Otherwise, we just submit a payload with the task type specified
36
else:
37
request_payload_string = f'[{{"task_type":"{tasktype}"}}]'
38
request_payload = json.loads(request_payload_string)
39
pprint.pprint(api_post_request(api_endpoint, request_payload))
40
print()
Copied!
The first part of this code block is mostly boilerplate that's similar to the previous commands we added:
1
@click.command(name="add-tasks")
2
@click.option('--tasktype', help='Type of task to submit.')
3
@click.option('--options', help='Key-value options for task.')
4
def add_tasks(tasktype, options):
5
"""Submit tasks to the listening post."""
6
api_endpoint = "/tasks"
7
print("\nHere are the tasks that were added:\n")
Copied!
We specify the name of the command and the options we're supporting. In the case of Add Tasks, we want to allow the user to select the task type and the options (if any) that the task type requires. We specify the endpoint and then print out a short message. We can now jump into the bulk of the command code:
1
# Perform options parsing if user provided them to the task
2
if options != None:
3
task_options_dict = {}
4
task_options_pairs = options.split(",")
5
6
# For each key-value pair, add them to a dictionary
7
for option in task_options_pairs:
8
key_vals = option.split("=")
9
key = key_vals[0]
10
value = key_vals[1]
11
pair = {key:value}
12
task_options_dict.update(pair)
13
14
# If more than one option was provided, format and append them into a single string
15
if len(task_options_dict) > 1:
16
keyval_string = ""
17
for key,value in task_options_dict.items():
18
keyval_string += f'"{key}":"{value}",'
19
request_payload_string = f'[{{"task_type":"{tasktype}",{keyval_string[:-1]}}}]'
20
request_payload = json.loads(request_payload_string)
21
pprint.pprint(api_post_request(api_endpoint, request_payload))
22
# Otherwise, just print the key/value for the single option provided
23
else:
24
request_payload_string = f'[{{"task_type":"{tasktype}","{key}":"{value}"}}]'
25
request_payload = json.loads(request_payload_string)
26
pprint.pprint(api_post_request(api_endpoint, request_payload))
Copied!
In the above code block, we have an if-conditional that checks to see if any options were provided for the task. If they were, we declare some variables to hold the task options dictionary of key-values and a variable to split up the key-value pairs. Next, we have a for-loop that splits each key-value pair and adds them to the task options dictionary as a new entry. Now, with our task options dictionary all filled out, we have another if-conditional that checks to see if we have more than one option. If we have several task options, we need to concatenate each key-value option and then add this string to our request payload. We then make the POST request and pretty print the listening post response. Otherwise, if we have a single task option, we can just use the key-value immediately without any for-loop and make the POST request.
In the case that no task options were provided, we have the following:
1
# Otherwise, we just submit a payload with the task type specified
2
else:
3
request_payload_string = f'[{{"task_type":"{tasktype}"}}]'
4
request_payload = json.loads(request_payload_string)
5
pprint.pprint(api_post_request(api_endpoint, request_payload))
6
print()
Copied!
With the above code block, we don't need to parse any task options and can just make a POST request with the task type. We then pretty print the listening post response.
The last part that needs to be modified is the section that adds each command to the CLI:
1
# Add commands to CLI
2
cli.add_command(list_tasks)
3
cli.add_command(list_results)
4
cli.add_command(list_history)
5
cli.add_command(add_tasks)
Copied!
As you can see, we've got a new line that specifies "add_tasks". With that final change, we're ready to test out our newly added command.

Add Tasks Test Drive

Ensure that the listening post and implant are both running. Now, run the following command to add a Ping task:
1
python fireworks.py add-tasks --tasktype ping
Copied!
You should get back a response similar to the following if things have gone well:
1
Here are the tasks that were added:
2
3
[{'_id': {'$oid': '5f6ef011363fb42173b13a4e'},
4
'task_id': '1fcbd838-e800-4da3-9765-b4a15656abb7',
5
'task_type': 'ping'}]
Copied!
You can wait a few moments and then run the following to see the results:
1
python fireworks.py list-results
Copied!
You'll get back:
1
Here's the results:
2
3
[{'1fcbd838-e800-4da3-9765-b4a15656abb7': {'contents': 'PONG!',
4
'success': 'true'},
5
'_id': {'$oid': '5f6ef025363fb42173b13a50'},
6
'result_id': '02848048-9179-4b6b-b9b6-3aa7db2e5281'}]
Copied!
Let's try adding a task with an option now. Run the following to add an Execute task with a command of "ping google.com":
1
python fireworks.py add-tasks --tasktype execute --options command="ping google.com"
Copied!
You'll get back:
1
Here are the tasks that were added:
2
3
[{'_id': {'$oid': '5f6ef162363fb42173b13a51'},
4
'command': 'ping google.com',
5
'task_id': '70492646-6ff1-490a-82de-1d703dfb1bf2',
6
'task_type': 'execute'}]
Copied!
You can run the List Results command again to see the following:
1
Here's the results:
2
3
[{'1fcbd838-e800-4da3-9765-b4a15656abb7': {'contents': 'PONG!',
4
'success': 'true'},
5
'_id': {'$oid': '5f6ef025363fb42173b13a50'},
6
'result_id': '02848048-9179-4b6b-b9b6-3aa7db2e5281'},
7
{'70492646-6ff1-490a-82de-1d703dfb1bf2': {'contents': '\n'
8
'Pinging google.com '
9
'[172.217.164.206] with '
10
'32 bytes of data:\n'
11
'Reply from '
12
'172.217.164.206: '
13
'bytes=32 time=3ms '
14
'TTL=115\n'
15
'Reply from '
16
'172.217.164.206: '
17
'bytes=32 time=3ms '
18
'TTL=115\n'
19
'Reply from '
20
'172.217.164.206: '
21
'bytes=32 time=3ms '
22
'TTL=115\n'
23
'Reply from '
24
'172.217.164.206: '
25
'bytes=32 time=3ms '
26
'TTL=115\n'
27
'\n'
28
'Ping statistics for '
29
'172.217.164.206:\n'
30
' Packets: Sent = 4, '
31
'Received = 4, Lost = 0 '
32
'(0% loss),\n'
33
'Approximate round trip '
34
'times in '
35
'milli-seconds:\n'
36
' Minimum = 3ms, '
37
'Maximum = 3ms, Average '
38
'= 3ms\n',
39
'success': 'true'},
40
'_id': {'$oid': '5f6ef169363fb42173b13a53'},
41
'result_id': '334e866e-d424-4081-a941-d8eda35b0ea5'}]
Copied!
You can see that the results of the ping were successfully populated and we've confirmed that our CLI client is working properly with the new Add Tasks command!

Conclusion

We now have a more comfortable interface from which to send tasks and see results, quite a bit of a step up from pasting PowerShell commands right? With this piece, we've got a fully functional C2 setup with an operator interface, listening post and implant. Each of the pieces are relatively simple, but that just gives us more room to build on and expand with more advanced components later on.

Further Reading & Next Steps

To learn more about CLI clients for C2, check out the following projects which employ CLI clients in an excellent fashion:
Last modified 11mo ago