Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix django bugs #16

Merged
merged 37 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from 35 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
91f44fc
Make sure manage.py calls "django" specifically
Jul 23, 2024
025b338
Update django-gunicorn app to use form data instead of url
Jul 23, 2024
63d5210
Add healthcheck to django-mysql-gunicorn application
Jul 23, 2024
2725e1a
Fix bugs with create_dog.html page
Jul 23, 2024
e1b1d89
Use os.fork, this fixes issues with django
Jul 23, 2024
0eefb54
It's a process not a thread, change this for clarity
Jul 23, 2024
650e3dd
Remove pymysql from sample-django apps and use mysqlcient instead (th…
Jul 23, 2024
edfca35
allow running without server and allow running server-only
Jul 23, 2024
be03cf0
Remove aikido imports from manage.py file
Jul 23, 2024
2932a80
Add gunicorn config file
Jul 23, 2024
7bd21da
Linting
Jul 23, 2024
4be81d2
Add django-gunicorn parsing
Jul 23, 2024
40211b6
django-gunicorn add to supported sources
Jul 23, 2024
45b2fea
Read body and rewrite it
Jul 23, 2024
b6b8c39
set_as_current_context
Jul 23, 2024
e560f2c
Cleanup config and make special "django-gunicorn" class
Jul 23, 2024
4d54f81
Merge branch 'main' into AIK-3199
bitterpanda63 Jul 25, 2024
1fd4c35
Merge remote-tracking branch 'origin/AIK-3167' into AIK-3199
Jul 29, 2024
00c3dd3
Linting after merge
Jul 29, 2024
f950962
Update test suite to use new reset_comms function
Jul 29, 2024
73c5fa4
Create reset_comms function and at timeout to sending data over IPC
Jul 29, 2024
8c3c04e
Add comments, "KILL" action and check if port is already in use
Jul 29, 2024
20e0ab6
Move send code to a thread
Jul 29, 2024
73c9205
Fix bugs with django-mysql sample app
Jul 30, 2024
d5d2384
Fix dogpage as well
Jul 30, 2024
60f7790
Merge branch 'main' into AIK-3199
willem-delbare Jul 30, 2024
48e05f2
Update aikido_firewall/background_process/__init__.py
willem-delbare Jul 30, 2024
80151a7
Renaming and splitting up files
Jul 30, 2024
4480e2b
Ignore global pylint error and explain threading (coomentz)
Jul 30, 2024
3dbf878
Split up testing, remove unused imports
Jul 30, 2024
9968b2e
Linting and import comms
Jul 30, 2024
c586dbb
Linting comment
Jul 30, 2024
673c889
Move gunicorn code to a file so our gunicorn config file is smaller
Jul 30, 2024
7f8f8aa
Merge branch 'AIK-3199' into move-ipc-to-seperate-file
bitterpanda63 Jul 30, 2024
7be09d2
Merge pull request #27 from AikidoSec/move-ipc-to-seperate-file
bitterpanda63 Jul 30, 2024
b212ef0
Rename "server-only" to "background-process-only"
Jul 30, 2024
2e2f63d
Update aikido_firewall/background_process/aikido_background_process.py
willem-delbare Jul 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions aikido_firewall/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,25 @@
load_dotenv()


def protect(module="any"):
def protect(module="any", server=True):
"""
Protect user's application
"""
if server:
start_background_process()
else:
logger.debug("Not starting background process")

Check warning on line 25 in aikido_firewall/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/__init__.py#L25

Added line #L25 was not covered by tests
if module == "server-only":
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rename

return

Check warning on line 27 in aikido_firewall/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/__init__.py#L27

Added line #L27 was not covered by tests

# Import sources
import aikido_firewall.sources.django
if module == "django":
import aikido_firewall.sources.django

if module != "django":
if not module in ["django", "django-gunicorn"]:
import aikido_firewall.sources.flask

# Import sinks
import aikido_firewall.sinks.pymysql

logger.info("Aikido python firewall started")
start_background_process()
116 changes: 8 additions & 108 deletions aikido_firewall/background_process/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,124 +3,24 @@
and listen for data sent by our sources and sinks
"""

import time
import os
import secrets
import multiprocessing.connection as con
from multiprocessing import Process
from threading import Thread
from queue import Queue
from aikido_firewall.helpers.logging import logger
from aikido_firewall.background_process.comms import (
AikidoIPCCommunications,
get_comms,
reset_comms,
)

REPORT_SEC_INTERVAL = 600 # 10 minutes
IPC_ADDRESS = ("localhost", 9898) # Specify the IP address and port


class AikidoBackgroundProcess:
"""
Aikido's background process consists of 2 threads :
- (main) Listening thread which listens on an IPC socket for incoming data
- (spawned) reporting thread which will collect the IPC data and send it to a Reporter
"""

def __init__(self, address, key):
logger.debug("Background process started")
listener = con.Listener(address, authkey=key)
self.queue = Queue()
# Start reporting thread :
Thread(target=self.reporting_thread).start()

while True:
conn = listener.accept()
logger.debug("connection accepted from %s", listener.last_accepted)
while True:
data = conn.recv()
logger.error(data) # Temporary debugging
if data[0] == "ATTACK":
self.queue.put(data[1])
elif data[0] == "CLOSE": # this is a kind of EOL for python IPC
conn.close()
break

def reporting_thread(self):
"""Reporting thread"""
logger.debug("Started reporting thread")
while True:
self.send_to_reporter()
time.sleep(REPORT_SEC_INTERVAL)

def send_to_reporter(self):
"""
Reports the found data to an Aikido server
"""
items_to_report = []
while not self.queue.empty():
items_to_report.append(self.queue.get())
logger.debug("Reporting to aikido server")
logger.critical("Items to report : %s", items_to_report)
# Currently not making API calls


# pylint: disable=invalid-name # This variable does change
ipc = None


def get_comms():
"""
Returns the globally stored IPC object, which you need
to communicate to our background process.
"""
return ipc


def start_background_process():
"""
Starts a process to handle incoming/outgoing data
"""
# pylint: disable=global-statement # We need this to be global
global ipc

# Generate a secret key :
generated_key_bytes = secrets.token_bytes(32)
willem-delbare marked this conversation as resolved.
Show resolved Hide resolved

ipc = IPC(IPC_ADDRESS, generated_key_bytes)
ipc.start_aikido_listener()


class IPC:
"""
Facilitates Inter-Process communication
"""

def __init__(self, address, key):
self.address = address
self.key = key
self.background_process = None

def start_aikido_listener(self):
"""
This will start the aikido background process which listens
and makes calls to the API
"""
self.background_process = Process(
target=AikidoBackgroundProcess,
args=(
self.address,
self.key,
),
)
logger.debug("Starting the background process")
self.background_process.start()

def send_data(self, action, obj):
"""
This creates a new client for comms to the background process
"""
try:
conn = con.Client(self.address, authkey=self.key)
logger.debug("Created connection %s", conn)
conn.send((action, obj))
conn.send(("CLOSE", {}))
conn.close()
logger.debug("Connection closed")
except Exception as e:
logger.info("Failed to send data to bg process : %s", e)
comms = AikidoIPCCommunications(IPC_ADDRESS, generated_key_bytes)
comms.start_aikido_listener()
72 changes: 72 additions & 0 deletions aikido_firewall/background_process/aikido_background_process.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""
Simply exports the aikido background process
"""

import multiprocessing.connection as con
import os
import time
import signal
from threading import Thread
from queue import Queue
from aikido_firewall.helpers.logging import logger

REPORT_SEC_INTERVAL = 600 # 10 minutes


class AikidoBackgroundProcess:
"""
Aikido's background process consists of 2 threads :
- (main) Listening thread which listens on an IPC socket for incoming data
- (spawned) reporting thread which will collect the IPC data and send it to a Reporter
"""

def __init__(self, address, key):
logger.debug("Background process started")
try:
listener = con.Listener(address, authkey=key)
except OSError:
logger.warning(

Check warning on line 28 in aikido_firewall/background_process/aikido_background_process.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/aikido_background_process.py#L24-L28

Added lines #L24 - L28 were not covered by tests
"Aikido listener may already be running on port %s", address[1]
)
pid = os.getpid()
os.kill(pid, signal.SIGTERM) # Kill this subprocess
self.queue = Queue()

Check warning on line 33 in aikido_firewall/background_process/aikido_background_process.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/aikido_background_process.py#L31-L33

Added lines #L31 - L33 were not covered by tests
# Start reporting thread :
Thread(target=self.reporting_thread).start()

Check warning on line 35 in aikido_firewall/background_process/aikido_background_process.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/aikido_background_process.py#L35

Added line #L35 was not covered by tests

while True:
conn = listener.accept()
logger.debug("connection accepted from %s", listener.last_accepted)
while True:
data = conn.recv()
willem-delbare marked this conversation as resolved.
Show resolved Hide resolved
logger.debug("Incoming data : %s", data)
if data[0] == "ATTACK":
self.queue.put(data[1])
elif data[0] == "CLOSE": # this is a kind of EOL for python IPC
conn.close()
break
elif (

Check warning on line 48 in aikido_firewall/background_process/aikido_background_process.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/aikido_background_process.py#L37-L48

Added lines #L37 - L48 were not covered by tests
data[0] == "KILL"
): # when main process quits , or during testing etc
logger.debug("Killing subprocess")
conn.close()
pid = os.getpid()
os.kill(pid, signal.SIGTERM) # Kill this subprocess

Check warning on line 54 in aikido_firewall/background_process/aikido_background_process.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/aikido_background_process.py#L51-L54

Added lines #L51 - L54 were not covered by tests

def reporting_thread(self):
"""Reporting thread"""
logger.debug("Started reporting thread")
while True:
self.send_to_reporter()
time.sleep(REPORT_SEC_INTERVAL)

Check warning on line 61 in aikido_firewall/background_process/aikido_background_process.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/aikido_background_process.py#L58-L61

Added lines #L58 - L61 were not covered by tests
willem-delbare marked this conversation as resolved.
Show resolved Hide resolved

def send_to_reporter(self):
"""
Reports the found data to an Aikido server
"""
items_to_report = []
while not self.queue.empty():
items_to_report.append(self.queue.get())
logger.debug("Reporting to aikido server")
logger.critical("Items to report : %s", items_to_report)

Check warning on line 71 in aikido_firewall/background_process/aikido_background_process.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/aikido_background_process.py#L67-L71

Added lines #L67 - L71 were not covered by tests
# Currently not making API calls
83 changes: 83 additions & 0 deletions aikido_firewall/background_process/comms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""
Holds the globally stored comms object
Exports the AikidoIPCCommunications class
"""

import os
import multiprocessing.connection as con
from threading import Thread
from aikido_firewall.helpers.logging import logger
from aikido_firewall.background_process.aikido_background_process import (
AikidoBackgroundProcess,
)

# pylint: disable=invalid-name # This variable does change
comms = None


def get_comms():
"""
Returns the globally stored IPC object, which you need
to communicate to our background process.
"""
return comms


def reset_comms():
"""This will reset communications"""
# pylint: disable=global-statement # This needs to be global
global comms
if comms:
comms.send_data_to_bg_process("KILL", {})
comms = None


class AikidoIPCCommunications:
"""
Facilitates Inter-Process communication
"""

def __init__(self, address, key):
# The key needs to be in byte form
self.address = address
self.key = key

# Set as global ipc object :
reset_comms()
# pylint: disable=global-statement # This needs to be global
global comms
comms = self

def start_aikido_listener(self):
"""This will start the aikido process which listens"""
pid = os.fork()
if pid == 0: # Child process
AikidoBackgroundProcess(self.address, self.key)

Check warning on line 55 in aikido_firewall/background_process/comms.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/comms.py#L55

Added line #L55 was not covered by tests
else: # Parent process
logger.debug("Started background process, PID: %d", pid)

def send_data_to_bg_process(self, action, obj):
"""
This creates a new client for comms to the background process
"""

# We want to make sure that sending out this data affects the process as little as possible
# So we run it inside a seperate thread with a timeout of 3 seconds
def target(address, key, data_array):
try:
conn = con.Client(address, authkey=key)
logger.debug("Created connection %s", conn)
for data in data_array:
conn.send(data)
conn.send(("CLOSE", {}))
conn.close()
logger.debug("Connection closed")
except Exception as e:
logger.info("Failed to send data to bg process : %s", e)

t = Thread(
target=target, args=(self.address, self.key, [(action, obj)]), daemon=True
)
t.start()
# This joins the thread for 3 seconds, afterwards the thread is forced to close (daemon=True)
t.join(timeout=3)
31 changes: 31 additions & 0 deletions aikido_firewall/background_process/comms_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import pytest
from aikido_firewall.background_process.comms import AikidoIPCCommunications


def test_comms_init():
address = ("localhost", 9898)
key = "secret_key"
comms = AikidoIPCCommunications(address, key)

assert comms.address == address
assert comms.key == key


def test_send_data_to_bg_process_exception(monkeypatch, caplog):
def mock_client(address, authkey):
raise Exception("Connection Error")

Check warning on line 16 in aikido_firewall/background_process/comms_test.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/comms_test.py#L16

Added line #L16 was not covered by tests

monkeypatch.setitem(globals(), "Client", mock_client)
monkeypatch.setitem(globals(), "logger", caplog)

comms = AikidoIPCCommunications(("localhost", 9898), "mock_key")
comms.send_data_to_bg_process("ACTION", "Test Object")


def test_send_data_to_bg_process_successful(monkeypatch, caplog, mocker):
comms = AikidoIPCCommunications(("localhost"), "mock_key")
mock_client = mocker.MagicMock()
monkeypatch.setattr("multiprocessing.connection.Client", mock_client)

# Call the send_data_to_bg_process function
comms.send_data_to_bg_process("ACTION", {"key": "value"})
Loading
Loading