Skip to content

Fix django bugs #16

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

Merged
merged 37 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from 26 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()
76 changes: 51 additions & 25 deletions aikido_firewall/background_process/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import time
import os
import secrets
import signal
import socket
import multiprocessing.connection as con
from multiprocessing import Process
from threading import Thread
Expand All @@ -25,7 +27,14 @@

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

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

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/__init__.py#L30-L33

Added lines #L30 - L33 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

Check warning on line 37 in aikido_firewall/background_process/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/__init__.py#L36-L37

Added lines #L36 - L37 were not covered by tests
self.queue = Queue()
# Start reporting thread :
Thread(target=self.reporting_thread).start()
Expand All @@ -35,12 +44,17 @@
logger.debug("connection accepted from %s", listener.last_accepted)
while True:
data = conn.recv()
logger.error(data) # Temporary debugging
logger.debug("Incoming data : %s", data)

Check warning on line 47 in aikido_firewall/background_process/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/__init__.py#L47

Added line #L47 was not covered by tests
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":
logger.debug("Killing subprocess")
conn.close()
pid = os.getpid()
os.kill(pid, signal.SIGTERM) # Kill this subprocess

Check warning on line 57 in aikido_firewall/background_process/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/__init__.py#L53-L57

Added lines #L53 - L57 were not covered by tests

def reporting_thread(self):
"""Reporting thread"""
Expand Down Expand Up @@ -73,6 +87,14 @@
return ipc


def reset_comms():
"""This will reset communications"""
global ipc
if ipc:
ipc.send_data("KILL", {})
ipc = None


def start_background_process():
"""
Starts a process to handle incoming/outgoing data
Expand All @@ -92,35 +114,39 @@
"""

def __init__(self, address, key):
# The key needs to be in byte form
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()
"""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 125 in aikido_firewall/background_process/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/background_process/__init__.py#L125

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

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)

# 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()
t.join(timeout=3)
11 changes: 5 additions & 6 deletions aikido_firewall/background_process/init_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
start_background_process,
get_comms,
IPC_ADDRESS,
reset_comms,
)


Expand All @@ -13,18 +14,19 @@ def test_ipc_init():
ipc = IPC(address, key)

assert ipc.address == address
assert ipc.background_process is None
assert ipc.key == key


# Following function does not work
def test_start_background_process(monkeypatch):
reset_comms()
assert get_comms() == None
start_background_process()

assert get_comms() != None
assert get_comms().address == IPC_ADDRESS

get_comms().background_process.kill()
reset_comms()
assert get_comms() == None


def test_send_data_exception(monkeypatch, caplog):
Expand All @@ -37,9 +39,6 @@ def mock_client(address, authkey):
ipc = IPC(("localhost", 9898), "mock_key")
ipc.send_data("ACTION", "Test Object")

assert "Failed to send data to bg" in caplog.text
# Add assertions for handling exceptions


def test_send_data_successful(monkeypatch, caplog, mocker):
ipc = IPC(("localhost"), "mock_key")
Expand Down
33 changes: 32 additions & 1 deletion aikido_firewall/context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
"""

import threading
from urllib.parse import parse_qs
from http.cookies import SimpleCookie

SUPPORTED_SOURCES = ["django", "flask"]

SUPPORTED_SOURCES = ["django", "flask", "django-gunicorn"]
UINPUT_SOURCES = ["body", "cookies", "query", "headers"]

local = threading.local()
Expand All @@ -22,9 +25,26 @@
"""Parse EnvironHeaders object into a dict"""
if isinstance(headers, dict):
return headers
if isinstance(headers, list):
obj = {}
for k, v in headers:
obj[k] = v
return obj

Check warning on line 32 in aikido_firewall/context/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/context/__init__.py#L29-L32

Added lines #L29 - L32 were not covered by tests
return dict(zip(headers.keys(), headers.values()))


def parse_cookies(cookie_str):
"""Parse cookie string from headers"""
cookie_dict = {}
cookies = SimpleCookie()
cookies.load(cookie_str)

Check warning on line 40 in aikido_firewall/context/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/context/__init__.py#L38-L40

Added lines #L38 - L40 were not covered by tests

for key, morsel in cookies.items():
cookie_dict[key] = morsel.value

Check warning on line 43 in aikido_firewall/context/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/context/__init__.py#L42-L43

Added lines #L42 - L43 were not covered by tests

return cookie_dict

Check warning on line 45 in aikido_firewall/context/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/context/__init__.py#L45

Added line #L45 was not covered by tests


class Context:
"""
A context object, it stores everything that is important
Expand All @@ -41,6 +61,17 @@
self.set_flask_attrs(req)
elif source == "django":
self.set_django_attrs(req)
elif source == "django-gunicorn":
self.set_django_gunicorn_attrs(req)

Check warning on line 65 in aikido_firewall/context/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/context/__init__.py#L64-L65

Added lines #L64 - L65 were not covered by tests

def set_django_gunicorn_attrs(self, req):
"""Set properties that are specific to django-gunicorn"""
self.remote_address = req.remote_addr
self.url = req.uri
self.body = parse_qs(req.body_copy.decode("utf-8"))
self.query = parse_qs(req.query)
self.cookies = parse_cookies(self.headers["COOKIE"])
del self.headers["COOKIE"]

Check warning on line 74 in aikido_firewall/context/__init__.py

View check run for this annotation

Codecov / codecov/patch

aikido_firewall/context/__init__.py#L69-L74

Added lines #L69 - L74 were not covered by tests

def set_django_attrs(self, req):
"""set properties that are specific to django"""
Expand Down
5 changes: 3 additions & 2 deletions aikido_firewall/init_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest
from aikido_firewall import protect
from aikido_firewall.background_process import get_comms
from aikido_firewall.background_process import get_comms, reset_comms


def test_protect_with_django(monkeypatch, caplog):
Expand All @@ -15,4 +15,5 @@ def test_protect_with_django(monkeypatch, caplog):

assert "Aikido python firewall started" in caplog.text
assert get_comms() != None
get_comms().background_process.kill()
reset_comms()
assert get_comms() == None
4 changes: 2 additions & 2 deletions sample-apps/django-mysql-gunicorn/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ This will expose a Django web server at [localhost:8080](http://localhost:8080)

## URLS :
- Homepage : `http://localhost:8080/app`
- Create a dog : `http://localhost:8080/app/create/<dog_name>`
- MySQL attack : `http://localhost:8080/app/create/Malicious dog", "Injected wrong boss name"); --%20`
- Create a dog : `http://localhost:8080/app/create/`
- MySQL attack : Enter `Malicious dog", "Injected wrong boss name"); -- `

To verify your attack was successfully note that the boss_name usualy is 'N/A', if you open the dog page (you can do this from the home page). You should see a "malicious dog" with a boss name that is not permitted.
12 changes: 9 additions & 3 deletions sample-apps/django-mysql-gunicorn/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version: '3'
services:
db:
image: mysql
image: mariadb
container_name: django_mysql_gunicorn_mariadb
restart: always
volumes:
Expand All @@ -17,13 +17,18 @@ services:
expose:
# Opens port 3306 on the container
- '3306'
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 5s
retries: 5
start_period: 10s

backend:
build:
context: ./../../
dockerfile: ./sample-apps/django-mysql-gunicorn/Dockerfile
container_name: django_mysql_gunicorn_backend
command: sh -c "python manage.py migrate && gunicorn --workers 4 --threads 2 --log-level debug --access-logfile '-' --error-logfile '-' --bind 0.0.0.0:8000 sample-django-mysql-gunicorn-app.wsgi"
command: sh -c "python manage.py migrate && gunicorn -c gunicorn_config.py --workers 4 --threads 2 --log-level debug --access-logfile '-' --error-logfile '-' --bind 0.0.0.0:8000 sample-django-mysql-gunicorn-app.wsgi"
restart: always
volumes:
- .:/app
Expand All @@ -32,7 +37,8 @@ services:
env_file:
- .env
depends_on:
- db
db:
condition: service_healthy

volumes:
db_data:
39 changes: 39 additions & 0 deletions sample-apps/django-mysql-gunicorn/gunicorn_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import aikido_firewall
import json
from urllib.parse import parse_qs
from io import BytesIO
from aikido_firewall.context import Context
from gunicorn.http.body import Body

def when_ready(server):
aikido_firewall.protect("server-only")

def pre_fork(server, worker):
pass

def post_fork(server, worker):
print("----------------------> POST FORK")
import aikido_firewall
aikido_firewall.protect("django-gunicorn", False)

def pre_request(worker, req):
req.body, req.body_copy = clone_body(req.body)

django_context = Context(req, "django-gunicorn")
django_context.set_as_current_context()

worker.log.debug("%s %s", req.method, req.path)


def clone_body(body):
body_read = body.read()

# Read the body content into a buffer
body_buffer = BytesIO()
body_buffer.write(body_read)
body_buffer.seek(0)

# Create a new Body object with the same content
cloned_body = Body(body_buffer)

return (cloned_body, body_read)
3 changes: 0 additions & 3 deletions sample-apps/django-mysql-gunicorn/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@
import os
import sys


def main():
"""Run administrative tasks."""
import aikido_firewall # Aikido module
aikido_firewall.protect()
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample-django-mysql-gunicorn-app.settings')
try:
from django.core.management import execute_from_command_line
Expand Down
2 changes: 1 addition & 1 deletion sample-apps/django-mysql-gunicorn/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
django
pymysql
mysqlclient
python-decouple
cryptography
gunicorn
Original file line number Diff line number Diff line change
@@ -1,2 +0,0 @@
import pymysql
pymysql.install_as_MySQLdb()
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<h1>Create a New Dog</h1>
<form method="post">
{% csrf_token %}
<label for="dog_name">Dog Name:</label>
<input type="text" id="dog_name" name="dog_name">
<button type="submit">Create Dog</button>
</form>
4 changes: 2 additions & 2 deletions sample-apps/django-mysql-gunicorn/sample_app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
urlpatterns = [
path("", views.index, name="index"),
path("dogpage/<int:dog_id>", views.dog_page, name="dog_page"),
path("create/<dog_name>", views.create_dogpage, name="create"),
]
path("create/", views.create_dogpage, name="create"),
]
Loading
Loading