-
Notifications
You must be signed in to change notification settings - Fork 1
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
Fix django bugs #16
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
025b338
Update django-gunicorn app to use form data instead of url
63d5210
Add healthcheck to django-mysql-gunicorn application
2725e1a
Fix bugs with create_dog.html page
e1b1d89
Use os.fork, this fixes issues with django
0eefb54
It's a process not a thread, change this for clarity
650e3dd
Remove pymysql from sample-django apps and use mysqlcient instead (th…
edfca35
allow running without server and allow running server-only
be03cf0
Remove aikido imports from manage.py file
2932a80
Add gunicorn config file
7bd21da
Linting
4be81d2
Add django-gunicorn parsing
40211b6
django-gunicorn add to supported sources
45b2fea
Read body and rewrite it
b6b8c39
set_as_current_context
e560f2c
Cleanup config and make special "django-gunicorn" class
4d54f81
Merge branch 'main' into AIK-3199
bitterpanda63 1fd4c35
Merge remote-tracking branch 'origin/AIK-3167' into AIK-3199
00c3dd3
Linting after merge
f950962
Update test suite to use new reset_comms function
73c5fa4
Create reset_comms function and at timeout to sending data over IPC
8c3c04e
Add comments, "KILL" action and check if port is already in use
20e0ab6
Move send code to a thread
73c9205
Fix bugs with django-mysql sample app
d5d2384
Fix dogpage as well
60f7790
Merge branch 'main' into AIK-3199
willem-delbare 48e05f2
Update aikido_firewall/background_process/__init__.py
willem-delbare 80151a7
Renaming and splitting up files
4480e2b
Ignore global pylint error and explain threading (coomentz)
3dbf878
Split up testing, remove unused imports
9968b2e
Linting and import comms
c586dbb
Linting comment
673c889
Move gunicorn code to a file so our gunicorn config file is smaller
7f8f8aa
Merge branch 'AIK-3199' into move-ipc-to-seperate-file
bitterpanda63 7be09d2
Merge pull request #27 from AikidoSec/move-ipc-to-seperate-file
bitterpanda63 b212ef0
Rename "server-only" to "background-process-only"
2e2f63d
Update aikido_firewall/background_process/aikido_background_process.py
willem-delbare File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
72 changes: 72 additions & 0 deletions
72
aikido_firewall/background_process/aikido_background_process.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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( | ||
"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() | ||
# 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() | ||
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 ( | ||
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 | ||
|
||
def reporting_thread(self): | ||
"""Reporting thread""" | ||
logger.debug("Started reporting thread") | ||
while True: | ||
self.send_to_reporter() | ||
time.sleep(REPORT_SEC_INTERVAL) | ||
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) | ||
# Currently not making API calls |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
|
||
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"}) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
rename