Port hijack changes and start writing frontend
This commit is contained in:
@@ -11,7 +11,14 @@ class Service:
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, var: dict):
|
||||
return cls(id=var["service_id"], status=var["status"], port=var["port"], name=var["name"], proto=var["proto"], ip_int=var["ip_int"])
|
||||
return cls(
|
||||
id=var["service_id"],
|
||||
status=var["status"],
|
||||
port=var["port"],
|
||||
name=var["name"],
|
||||
proto=var["proto"],
|
||||
ip_int=var["ip_int"]
|
||||
)
|
||||
|
||||
|
||||
class Regex:
|
||||
@@ -27,4 +34,13 @@ class Regex:
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, var: dict):
|
||||
return cls(id=var["regex_id"], regex=base64.b64decode(var["regex"]), mode=var["mode"], service_id=var["service_id"], is_blacklist=var["is_blacklist"], blocked_packets=var["blocked_packets"], is_case_sensitive=var["is_case_sensitive"], active=var["active"])
|
||||
return cls(
|
||||
id=var["regex_id"],
|
||||
regex=base64.b64decode(var["regex"]),
|
||||
mode=var["mode"],
|
||||
service_id=var["service_id"],
|
||||
is_blacklist=var["is_blacklist"],
|
||||
blocked_packets=var["blocked_packets"],
|
||||
is_case_sensitive=var["is_case_sensitive"],
|
||||
active=var["active"]
|
||||
)
|
||||
@@ -1,6 +1,6 @@
|
||||
from typing import List
|
||||
from modules.nfregex.models import Service
|
||||
from utils import ip_parse, ip_family, NFTableManager
|
||||
from utils import ip_parse, ip_family, NFTableManager, nftables_int_to_json
|
||||
|
||||
class FiregexFilter:
|
||||
def __init__(self, proto:str, port:int, ip_int:str, target:str, id:int):
|
||||
@@ -52,10 +52,6 @@ class FiregexTables(NFTableManager):
|
||||
|
||||
for ele in self.get():
|
||||
if ele.__eq__(srv): return
|
||||
|
||||
ip_int = ip_parse(srv.ip_int)
|
||||
ip_addr = str(ip_int).split("/")[0]
|
||||
ip_addr_cidr = int(str(ip_int).split("/")[1])
|
||||
|
||||
init, end = queue_range_output
|
||||
if init > end: init, end = end, init
|
||||
@@ -64,7 +60,7 @@ class FiregexTables(NFTableManager):
|
||||
"table": self.table_name,
|
||||
"chain": self.output_chain,
|
||||
"expr": [
|
||||
{'match': {'left': {'payload': {'protocol': ip_family(ip_int), 'field': 'saddr'}}, 'op': '==', 'right': {"prefix": {"addr": ip_addr, "len": ip_addr_cidr}}}},
|
||||
{'match': {'left': {'payload': {'protocol': ip_family(srv.ip_int), 'field': 'saddr'}}, 'op': '==', 'right': nftables_int_to_json(srv.ip_int)}},
|
||||
{'match': {"left": { "payload": {"protocol": str(srv.proto), "field": "sport"}}, "op": "==", "right": int(srv.port)}},
|
||||
{"queue": {"num": str(init) if init == end else {"range":[init, end] }, "flags": ["bypass"]}}
|
||||
]
|
||||
@@ -77,7 +73,7 @@ class FiregexTables(NFTableManager):
|
||||
"table": self.table_name,
|
||||
"chain": self.input_chain,
|
||||
"expr": [
|
||||
{'match': {'left': {'payload': {'protocol': ip_family(ip_int), 'field': 'daddr'}}, 'op': '==', 'right': {"prefix": {"addr": ip_addr, "len": ip_addr_cidr}}}},
|
||||
{'match': {'left': {'payload': {'protocol': ip_family(srv.ip_int), 'field': 'daddr'}}, 'op': '==', 'right': nftables_int_to_json(srv.ip_int)}},
|
||||
{'match': {"left": { "payload": {"protocol": str(srv.proto), "field": "dport"}}, "op": "==", "right": int(srv.port)}},
|
||||
{"queue": {"num": str(init) if init == end else {"range":[init, end] }, "flags": ["bypass"]}}
|
||||
]
|
||||
|
||||
@@ -64,8 +64,8 @@ class ServiceManager:
|
||||
nft.delete(self.srv)
|
||||
self._set_status(False)
|
||||
|
||||
async def change_port(self, new_port):
|
||||
self.srv.proxy_port = new_port
|
||||
async def refresh(self, srv:Service):
|
||||
self.srv = srv
|
||||
if self.active: await self.restart()
|
||||
|
||||
def _set_status(self,active):
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
class Service:
|
||||
def __init__(self, service_id: str, active: bool, public_port: int, proxy_port: int, name: str, proto: str, ip_int: str):
|
||||
def __init__(self, service_id: str, active: bool, public_port: int, proxy_port: int, name: str, proto: str, ip_src: str, ip_dst:str):
|
||||
self.service_id = service_id
|
||||
self.active = active
|
||||
self.public_port = public_port
|
||||
self.proxy_port = proxy_port
|
||||
self.name = name
|
||||
self.proto = proto
|
||||
self.ip_int = ip_int
|
||||
self.ip_src = ip_src
|
||||
self.ip_dst = ip_dst
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, var: dict):
|
||||
return cls(service_id=var["service_id"], active=var["active"], public_port=var["public_port"], proxy_port=var["proxy_port"], name=var["name"], proto=var["proto"], ip_int=var["ip_int"])
|
||||
return cls(
|
||||
service_id=var["service_id"],
|
||||
active=var["active"],
|
||||
public_port=var["public_port"],
|
||||
proxy_port=var["proxy_port"],
|
||||
name=var["name"],
|
||||
proto=var["proto"],
|
||||
ip_src=var["ip_src"],
|
||||
ip_dst=var["ip_dst"]
|
||||
)
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
from typing import List
|
||||
from modules.porthijack.models import Service
|
||||
from utils import ip_parse, ip_family, NFTableManager
|
||||
from utils import addr_parse, ip_parse, ip_family, NFTableManager, nftables_json_to_int
|
||||
|
||||
class FiregexHijackRule():
|
||||
def __init__(self, proto:str, public_port:int,proxy_port:int, ip_int:str, target:str, id:int):
|
||||
def __init__(self, proto:str, public_port:int,proxy_port:int, ip_src:str, ip_dst:str, target:str, id:int):
|
||||
self.id = id
|
||||
self.target = target
|
||||
self.proto = proto
|
||||
self.public_port = public_port
|
||||
self.proxy_port = proxy_port
|
||||
self.ip_int = str(ip_int)
|
||||
self.ip_src = str(ip_src)
|
||||
self.ip_dst = str(ip_dst)
|
||||
|
||||
def __eq__(self, o: object) -> bool:
|
||||
if isinstance(o, FiregexHijackRule):
|
||||
return self.public_port == o.public_port and self.proto == o.proto and ip_parse(self.ip_int) == ip_parse(o.ip_int)
|
||||
return self.public_port == o.public_port and self.proto == o.proto and ip_parse(self.ip_src) == ip_parse(o.ip_src)
|
||||
elif isinstance(o, Service):
|
||||
return self.public_port == o.public_port and self.proto == o.proto and ip_parse(self.ip_int) == ip_parse(o.ip_int)
|
||||
return self.public_port == o.public_port and self.proto == o.proto and ip_parse(self.ip_src) == ip_parse(o.ip_src)
|
||||
return False
|
||||
|
||||
class FiregexTables(NFTableManager):
|
||||
@@ -54,17 +55,15 @@ class FiregexTables(NFTableManager):
|
||||
for ele in self.get():
|
||||
if ele.__eq__(srv): return
|
||||
|
||||
ip_int = ip_parse(srv.ip_int)
|
||||
ip_addr = str(ip_int).split("/")[0]
|
||||
ip_addr_cidr = int(str(ip_int).split("/")[1])
|
||||
self.cmd({ "insert":{ "rule": {
|
||||
"family": "inet",
|
||||
"table": self.table_name,
|
||||
"chain": self.prerouting_porthijack,
|
||||
"expr": [
|
||||
{'match': {'left': {'payload': {'protocol': ip_family(ip_int), 'field': 'daddr'}}, 'op': '==', 'right': {"prefix": {"addr": ip_addr, "len": ip_addr_cidr}}}},
|
||||
{'match': {'left': { "payload": {"protocol": str(srv.proto), "field": "dport"}}, "op": "==", "right": int(srv.public_port)}},
|
||||
{'mangle': {'key': {'payload': {'protocol': str(srv.proto), 'field': 'dport'}}, 'value': int(srv.proxy_port)}}
|
||||
{'match': {'left': {'payload': {'protocol': ip_family(srv.ip_src), 'field': 'daddr'}}, 'op': '==', 'right': addr_parse(srv.ip_src)}},
|
||||
{'match': {'left': {'payload': {'protocol': str(srv.proto), 'field': 'dport'}}, 'op': '==', 'right': int(srv.public_port)}},
|
||||
{'mangle': {'key': {'payload': {'protocol': str(srv.proto), 'field': 'dport'}}, 'value': int(srv.proxy_port)}},
|
||||
{'mangle': {'key': {'payload': {'protocol': ip_family(srv.ip_src), 'field': 'daddr'}}, 'value': addr_parse(srv.ip_dst)}}
|
||||
]
|
||||
}}})
|
||||
self.cmd({ "insert":{ "rule": {
|
||||
@@ -72,9 +71,10 @@ class FiregexTables(NFTableManager):
|
||||
"table": self.table_name,
|
||||
"chain": self.postrouting_porthijack,
|
||||
"expr": [
|
||||
{'match': {'left': {'payload': {'protocol': ip_family(ip_int), 'field': 'saddr'}}, 'op': '==', 'right': {"prefix": {"addr": ip_addr, "len": ip_addr_cidr}}}},
|
||||
{'match': {'left': {'payload': {'protocol': ip_family(srv.ip_dst), 'field': 'saddr'}}, 'op': '==', 'right': addr_parse(srv.ip_dst)}},
|
||||
{'match': {'left': { "payload": {"protocol": str(srv.proto), "field": "sport"}}, "op": "==", "right": int(srv.proxy_port)}},
|
||||
{'mangle': {'key': {'payload': {'protocol': str(srv.proto), 'field': 'sport'}}, 'value': int(srv.public_port)}}
|
||||
{'mangle': {'key': {'payload': {'protocol': str(srv.proto), 'field': 'sport'}}, 'value': int(srv.public_port)}},
|
||||
{'mangle': {'key': {'payload': {'protocol': ip_family(srv.ip_dst), 'field': 'saddr'}}, 'value': addr_parse(srv.ip_src)}}
|
||||
]
|
||||
}}})
|
||||
|
||||
@@ -82,18 +82,15 @@ class FiregexTables(NFTableManager):
|
||||
def get(self) -> List[FiregexHijackRule]:
|
||||
res = []
|
||||
for filter in self.list_rules(tables=[self.table_name], chains=[self.prerouting_porthijack,self.postrouting_porthijack]):
|
||||
ip_int = None
|
||||
if isinstance(filter["expr"][0]["match"]["right"],str):
|
||||
ip_int = str(ip_parse(filter["expr"][0]["match"]["right"]))
|
||||
else:
|
||||
ip_int = f'{filter["expr"][0]["match"]["right"]["prefix"]["addr"]}/{filter["expr"][0]["match"]["right"]["prefix"]["len"]}'
|
||||
filter["expr"][0]["match"]["right"]
|
||||
res.append(FiregexHijackRule(
|
||||
target=filter["chain"],
|
||||
id=int(filter["handle"]),
|
||||
proto=filter["expr"][1]["match"]["left"]["payload"]["protocol"],
|
||||
public_port=filter["expr"][1]["match"]["right"] if filter["chain"] == self.prerouting_porthijack else filter["expr"][2]["mangle"]["value"],
|
||||
proxy_port=filter["expr"][1]["match"]["right"] if filter["chain"] == self.postrouting_porthijack else filter["expr"][2]["mangle"]["value"],
|
||||
ip_int=ip_int
|
||||
ip_src=nftables_json_to_int(filter["expr"][0]["match"]["right"]) if filter["chain"] == self.prerouting_porthijack else nftables_json_to_int(filter["expr"][3]["mangle"]["value"]),
|
||||
ip_dst=nftables_json_to_int(filter["expr"][0]["match"]["right"]) if filter["chain"] == self.postrouting_porthijack else nftables_json_to_int(filter["expr"][3]["mangle"]["value"]),
|
||||
))
|
||||
return res
|
||||
|
||||
|
||||
@@ -3,8 +3,9 @@ import sqlite3
|
||||
from typing import List, Union
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from modules.porthijack.models import Service
|
||||
from utils.sqlite import SQLite
|
||||
from utils import ip_parse, refactor_name, refresh_frontend
|
||||
from utils import addr_parse, ip_family, refactor_name, refresh_frontend
|
||||
from utils.models import ResetRequest, StatusMessageModel
|
||||
from modules.porthijack.nftables import FiregexTables
|
||||
from modules.porthijack.firewall import FirewallManager
|
||||
@@ -16,7 +17,8 @@ class ServiceModel(BaseModel):
|
||||
proxy_port: int
|
||||
name: str
|
||||
proto: str
|
||||
ip_int: str
|
||||
ip_src: str
|
||||
ip_dst: str
|
||||
|
||||
class RenameForm(BaseModel):
|
||||
name:str
|
||||
@@ -26,7 +28,8 @@ class ServiceAddForm(BaseModel):
|
||||
public_port: int
|
||||
proxy_port: int
|
||||
proto: str
|
||||
ip_int: str
|
||||
ip_src: str
|
||||
ip_dst: str
|
||||
|
||||
class ServiceAddResponse(BaseModel):
|
||||
status:str
|
||||
@@ -41,15 +44,15 @@ db = SQLite('db/port-hijacking.db', {
|
||||
'services': {
|
||||
'service_id': 'VARCHAR(100) PRIMARY KEY',
|
||||
'active' : 'BOOLEAN NOT NULL CHECK (active IN (0, 1))',
|
||||
'public_port': 'INT NOT NULL CHECK(public_port > 0 and public_port < 65536) UNIQUE',
|
||||
'public_port': 'INT NOT NULL CHECK(public_port > 0 and public_port < 65536)',
|
||||
'proxy_port': 'INT NOT NULL CHECK(proxy_port > 0 and proxy_port < 65536 and proxy_port != public_port)',
|
||||
'name': 'VARCHAR(100) NOT NULL UNIQUE',
|
||||
'proto': 'VARCHAR(3) NOT NULL CHECK (proto IN ("tcp", "udp"))',
|
||||
'ip_int': 'VARCHAR(100) NOT NULL',
|
||||
'ip_src': 'VARCHAR(100) NOT NULL',
|
||||
'ip_dst': 'VARCHAR(100) NOT NULL',
|
||||
},
|
||||
'QUERY':[
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS unique_services ON services (public_port, ip_int, proto);",
|
||||
""
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS unique_services ON services (public_port, ip_src, proto);"
|
||||
]
|
||||
})
|
||||
|
||||
@@ -96,12 +99,12 @@ async def get_general_stats():
|
||||
@app.get('/services', response_model=List[ServiceModel])
|
||||
async def get_service_list():
|
||||
"""Get the list of existent firegex services"""
|
||||
return db.query("SELECT service_id, active, public_port, proxy_port, name, proto, ip_int FROM services;")
|
||||
return db.query("SELECT service_id, active, public_port, proxy_port, name, proto, ip_src, ip_dst FROM services;")
|
||||
|
||||
@app.get('/service/{service_id}', response_model=ServiceModel)
|
||||
async def get_service_by_id(service_id: str):
|
||||
"""Get info about a specific service using his id"""
|
||||
res = db.query("SELECT service_id, active, public_port, proxy_port, name, proto, ip_int FROM services WHERE service_id = ?;", service_id)
|
||||
res = db.query("SELECT service_id, active, public_port, proxy_port, name, proto, ip_src, ip_dst FROM services WHERE service_id = ?;", service_id)
|
||||
if len(res) == 0: raise HTTPException(status_code=400, detail="This service does not exists!")
|
||||
return res[0]
|
||||
|
||||
@@ -139,17 +142,30 @@ async def service_rename(service_id: str, form: RenameForm):
|
||||
await refresh_frontend()
|
||||
return {'status': 'ok'}
|
||||
|
||||
class ChangePortRequest(BaseModel):
|
||||
class ChangeDestination(BaseModel):
|
||||
ip_dst: str
|
||||
proxy_port: int
|
||||
|
||||
@app.post('/service/{service_id}/changeport', response_model=StatusMessageModel)
|
||||
async def service_changeport(service_id: str, form: ChangePortRequest):
|
||||
"""Request to change the proxy port of a specific service"""
|
||||
@app.post('/service/{service_id}/change-destination', response_model=StatusMessageModel)
|
||||
async def service_change_destination(service_id: str, form: ChangeDestination):
|
||||
"""Request to change the proxy destination of the service"""
|
||||
|
||||
try:
|
||||
db.query('UPDATE services SET proxy_port=? WHERE service_id = ?;', form.proxy_port, service_id)
|
||||
form.ip_dst = addr_parse(form.ip_dst)
|
||||
except ValueError:
|
||||
return {"status":"Invalid address"}
|
||||
srv = Service.from_dict(db.query('SELECT * FROM services WHERE service_id = ?;', service_id)[0])
|
||||
if ip_family(form.ip_dst) != ip_family(srv.ip_src):
|
||||
return {'status': 'The destination ip is not of the same family as the source ip'}
|
||||
try:
|
||||
db.query('UPDATE services SET proxy_port=?, ip_dst=? WHERE service_id = ?;', form.proxy_port, form.ip_dst, service_id)
|
||||
except sqlite3.IntegrityError:
|
||||
return {'status': 'Invalid proxy port or service'}
|
||||
await firewall.get(service_id).change_port(form.proxy_port)
|
||||
|
||||
srv.ip_dst = form.ip_dst
|
||||
srv.proxy_port = form.proxy_port
|
||||
await firewall.get(service_id).refresh(srv)
|
||||
|
||||
await refresh_frontend()
|
||||
return {'status': 'ok'}
|
||||
|
||||
@@ -157,18 +173,24 @@ async def service_changeport(service_id: str, form: ChangePortRequest):
|
||||
async def add_new_service(form: ServiceAddForm):
|
||||
"""Add a new service"""
|
||||
try:
|
||||
form.ip_int = ip_parse(form.ip_int)
|
||||
form.ip_src = addr_parse(form.ip_src)
|
||||
form.ip_dst = addr_parse(form.ip_dst)
|
||||
except ValueError:
|
||||
return {"status":"Invalid address"}
|
||||
|
||||
if ip_family(form.ip_dst) != ip_family(form.ip_src):
|
||||
return {"status":"Destination and source addresses must be of the same family"}
|
||||
if form.proto not in ["tcp", "udp"]:
|
||||
return {"status":"Invalid protocol"}
|
||||
|
||||
srv_id = None
|
||||
try:
|
||||
srv_id = gen_service_id()
|
||||
db.query("INSERT INTO services (service_id, active, public_port, proxy_port, name, proto, ip_int) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
srv_id, False, form.public_port, form.proxy_port , form.name, form.proto, form.ip_int)
|
||||
db.query("INSERT INTO services (service_id, active, public_port, proxy_port, name, proto, ip_src, ip_dst) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
srv_id, False, form.public_port, form.proxy_port , form.name, form.proto, form.ip_src, form.ip_dst)
|
||||
except sqlite3.IntegrityError:
|
||||
return {'status': 'This type of service already exists'}
|
||||
|
||||
await firewall.reload()
|
||||
await refresh_frontend()
|
||||
return {'status': 'ok', 'service_id': srv_id}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from ipaddress import ip_interface
|
||||
from ipaddress import ip_address, ip_interface
|
||||
import os, socket, psutil, sys, nftables
|
||||
from fastapi_socketio import SocketManager
|
||||
|
||||
@@ -37,6 +37,9 @@ def list_files(mypath):
|
||||
def ip_parse(ip:str):
|
||||
return str(ip_interface(ip).network)
|
||||
|
||||
def addr_parse(ip:str):
|
||||
return str(ip_address(ip))
|
||||
|
||||
def ip_family(ip:str):
|
||||
return "ip6" if ip_interface(ip).version == 6 else "ip"
|
||||
|
||||
@@ -48,6 +51,18 @@ def get_interfaces():
|
||||
yield {"name": int_name, "addr":interf.address}
|
||||
return list(_get_interfaces())
|
||||
|
||||
def nftables_int_to_json(ip_int):
|
||||
ip_int = ip_parse(ip_int)
|
||||
ip_addr = str(ip_int).split("/")[0]
|
||||
ip_addr_cidr = int(str(ip_int).split("/")[1])
|
||||
return {"prefix": {"addr": ip_addr, "len": ip_addr_cidr}}
|
||||
|
||||
def nftables_json_to_int(ip_json_int):
|
||||
if isinstance(ip_json_int,str):
|
||||
return str(ip_parse(ip_json_int))
|
||||
else:
|
||||
return f'{ip_json_int["prefix"]["addr"]}/{ip_json_int["prefix"]["len"]}'
|
||||
|
||||
class Singleton(object):
|
||||
__instance = None
|
||||
def __new__(class_, *args, **kwargs):
|
||||
|
||||
@@ -90,7 +90,7 @@ def load_routers(app):
|
||||
resets, startups, shutdowns = [], [], []
|
||||
for router in get_router_modules():
|
||||
if router.router:
|
||||
app.include_router(router.router, prefix=f"/{router.name}")
|
||||
app.include_router(router.router, prefix=f"/{router.name}", tags=[router.name])
|
||||
if router.reset:
|
||||
resets.append(router.reset)
|
||||
if router.startup:
|
||||
|
||||
Reference in New Issue
Block a user