Initial Commit

This commit is contained in:
Domingo Dirutigliano
2022-06-11 21:57:50 +02:00
committed by DomySh
commit 372ade7d6f
43 changed files with 30381 additions and 0 deletions

24
.gitignore vendored Executable file
View File

@@ -0,0 +1,24 @@
**/*.pyc
**/__pycache__/
/.vscode/**
**/node_modules
**/.pnp
**/.pnp.js
# testing
/frontend/coverage
# production
/frontend/build
# misc
**/.DS_Store
**/.env.local
**/.env.development.local
**/.env.test.local
**/.env.production.local
**/npm-debug.log*
**/yarn-debug.log*
**/yarn-error.log*

1
README.md Normal file
View File

@@ -0,0 +1 @@
# firegex

113
api-model.txt Executable file
View File

@@ -0,0 +1,113 @@
/api/general-stats
{
"services":1,
"closed":1,
"regex":1
}
#Processo di trasformazione del nome del servizio = primary_key
serv_id = serv_id.strip().replace(" ","-")
serv_id = "".join([c for c in serv_id if c in (strings.uppercase+strings.lowercase+strings.digits+"-")])
serv_id = serv_id.lower()
/api/services
[
{
"id":"serv_id",
"name":"text",
"status":"stop"/"wait"/"active"/"pause",
"public_port":1234,
"internal_port":44444,
"n_packets":1,
"n_regex":1,
}
]
/api/service/<serv>/stop
{
"status":"ok"
}
/api/service/<serv>/start
{
"status":"ok"
}
/api/service/<serv>/delete
{
"status":"ok"
}
/api/service/<serv>/terminate
{
"status":"ok"
}
/api/service/<serv>/regen-port
{
"status":"ok"
}
/api/service/<serv>/regexes
[
"5787":{
"regex":"base64"
"is_blacklist":true,
"mode":"C","S","B" // C->S S->C BOTH
}
]
/api/regex/<regex_id>
{
"service_id":"serv_id",
"regex":"base64"
"is_blacklist":true,
"mode":"C","S","B" // C->S S->C BOTH
}
/api/regex/<regex_id>/delete
{
"status":"ok"
}
/api/regexes/add POST
client
{
"service_id":"serv_id",
"regex":"base64",
"is_blacklist":true/false,
"mode":"C","S","B" // C->S S->C BOTH
}
server
{
"status":"ok"
}
/api/services/add POST
client
{
"name":"text",
"port":5362
}
server
{
"status":"ok"
}

6
backend/.dockerignore Executable file
View File

@@ -0,0 +1,6 @@
Dockerfile
docker-compose.yml
**/*.pyc
**/__pycache__/
/.vscode/**

19
backend/Dockerfile Executable file
View File

@@ -0,0 +1,19 @@
FROM python:3-buster
RUN apt-get update && apt-get -y install supervisor build-essential libboost-dev nginx
RUN mkdir /execute
WORKDIR /execute
ADD ./requirements.txt /execute/requirements.txt
RUN pip install --no-cache-dir -r /execute/requirements.txt
COPY . /execute/
COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./supervisord.conf /etc/supervisor/supervisord.conf
RUN usermod -a -G root nobody
RUN chown -R nobody:root /execute && \
chmod -R 660 /execute && chmod -R u+X /execute
ENTRYPOINT ["/usr/bin/supervisord","-c","/etc/supervisor/supervisord.conf"]

BIN
backend/c_back/proxy Executable file

Binary file not shown.

379
backend/c_back/proxy.cpp Normal file
View File

@@ -0,0 +1,379 @@
#include <cstdlib>
#include <cstddef>
#include <iostream>
#include <string>
#include <boost/regex.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread/mutex.hpp>
#include <cctype> // is*
//#define DEBUG
using namespace std;
int to_int(int c) {
if (not isxdigit(c)) return -1; // error: non-hexadecimal digit found
if (isdigit(c)) return c - '0';
if (isupper(c)) c = tolower(c);
return c - 'a' + 10;
}
template<class InputIterator, class OutputIterator> int
unhexlify(InputIterator first, InputIterator last, OutputIterator ascii) {
while (first != last) {
int top = to_int(*first++);
int bot = to_int(*first++);
if (top == -1 or bot == -1)
return -1; // error
*ascii++ = (top << 4) + bot;
}
return 0;
}
vector<pair<string,boost::regex>> regex_s_c_w, regex_c_s_w, regex_s_c_b, regex_c_s_b;
bool filter_data(unsigned char* data, const size_t& bytes_transferred, vector<pair<string,boost::regex>> const &blacklist, vector<pair<string,boost::regex>> const &whitelist){
#ifdef DEBUG
cout << "---------------- Packet ----------------" << endl;
for(int i=0;i<bytes_transferred;i++){
cout << data[i];
}
cout << "\n" << "---------------- End Packet ----------------" << endl;
#endif
for (pair<string,boost::regex> ele:blacklist){
boost::cmatch what;
if (boost::regex_match(reinterpret_cast<const char*>(data),
reinterpret_cast<const char*>(data) + bytes_transferred, what, ele.second)){
cout << "BLOCKED " << ele.first << endl;
return false;
}
}
for (pair<string,boost::regex> ele:whitelist){
boost::cmatch what;
if (!boost::regex_match(reinterpret_cast<const char*>(data),
reinterpret_cast<const char*>(data) + bytes_transferred, what, ele.second)){
cout << "BLOCKED " << ele.first << endl;
return false;
}
}
#ifdef DEBUG
cout << "Packet Accepted!" << endl;
#endif
return true;
}
namespace tcp_proxy
{
namespace ip = boost::asio::ip;
class bridge : public boost::enable_shared_from_this<bridge>
{
public:
typedef ip::tcp::socket socket_type;
typedef boost::shared_ptr<bridge> ptr_type;
bridge(boost::asio::io_service& ios)
: downstream_socket_(ios),
upstream_socket_ (ios)
{}
socket_type& downstream_socket()
{
// Client socket
return downstream_socket_;
}
socket_type& upstream_socket()
{
// Remote server socket
return upstream_socket_;
}
void start(const std::string& upstream_host, unsigned short upstream_port)
{
// Attempt connection to remote server (upstream side)
upstream_socket_.async_connect(
ip::tcp::endpoint(
boost::asio::ip::address::from_string(upstream_host),
upstream_port),
boost::bind(&bridge::handle_upstream_connect,
shared_from_this(),
boost::asio::placeholders::error));
}
void handle_upstream_connect(const boost::system::error_code& error)
{
if (!error)
{
// Setup async read from remote server (upstream)
upstream_socket_.async_read_some(
boost::asio::buffer(upstream_data_,max_data_length),
boost::bind(&bridge::handle_upstream_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
// Setup async read from client (downstream)
downstream_socket_.async_read_some(
boost::asio::buffer(downstream_data_,max_data_length),
boost::bind(&bridge::handle_downstream_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
close();
}
private:
/*
Section A: Remote Server --> Proxy --> Client
Process data recieved from remote sever then send to client.
*/
// Read from remote server complete, now send data to client
void handle_upstream_read(const boost::system::error_code& error,
const size_t& bytes_transferred) // Da Server a Client
{
if (!error)
{
if (filter_data(upstream_data_, bytes_transferred, regex_s_c_b, regex_s_c_w)){
async_write(downstream_socket_,
boost::asio::buffer(upstream_data_,bytes_transferred),
boost::bind(&bridge::handle_downstream_write,
shared_from_this(),
boost::asio::placeholders::error));
}else{
close();
}
}
else
close();
}
// Write to client complete, Async read from remote server
void handle_downstream_write(const boost::system::error_code& error)
{
if (!error)
{
upstream_socket_.async_read_some(
boost::asio::buffer(upstream_data_,max_data_length),
boost::bind(&bridge::handle_upstream_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
close();
}
// *** End Of Section A ***
/*
Section B: Client --> Proxy --> Remove Server
Process data recieved from client then write to remove server.
*/
// Read from client complete, now send data to remote server
void handle_downstream_read(const boost::system::error_code& error,
const size_t& bytes_transferred) // Da Client a Server
{
if (!error)
{
if (filter_data(downstream_data_, bytes_transferred, regex_c_s_b, regex_c_s_w)){
async_write(upstream_socket_,
boost::asio::buffer(downstream_data_,bytes_transferred),
boost::bind(&bridge::handle_upstream_write,
shared_from_this(),
boost::asio::placeholders::error));
}else{
close();
}
}
else
close();
}
// Write to remote server complete, Async read from client
void handle_upstream_write(const boost::system::error_code& error)
{
if (!error)
{
downstream_socket_.async_read_some(
boost::asio::buffer(downstream_data_,max_data_length),
boost::bind(&bridge::handle_downstream_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
close();
}
// *** End Of Section B ***
void close()
{
boost::mutex::scoped_lock lock(mutex_);
if (downstream_socket_.is_open())
{
downstream_socket_.close();
}
if (upstream_socket_.is_open())
{
upstream_socket_.close();
}
}
socket_type downstream_socket_;
socket_type upstream_socket_;
enum { max_data_length = 8192 }; //8KB
unsigned char downstream_data_[max_data_length];
unsigned char upstream_data_ [max_data_length];
boost::mutex mutex_;
public:
class acceptor
{
public:
acceptor(boost::asio::io_service& io_service,
const std::string& local_host, unsigned short local_port,
const std::string& upstream_host, unsigned short upstream_port)
: io_service_(io_service),
localhost_address(boost::asio::ip::address_v4::from_string(local_host)),
acceptor_(io_service_,ip::tcp::endpoint(localhost_address,local_port)),
upstream_port_(upstream_port),
upstream_host_(upstream_host)
{}
bool accept_connections()
{
try
{
session_ = boost::shared_ptr<bridge>(new bridge(io_service_));
acceptor_.async_accept(session_->downstream_socket(),
boost::bind(&acceptor::handle_accept,
this,
boost::asio::placeholders::error));
}
catch(std::exception& e)
{
std::cerr << "acceptor exception: " << e.what() << std::endl;
return false;
}
return true;
}
private:
void handle_accept(const boost::system::error_code& error)
{
if (!error)
{
session_->start(upstream_host_,upstream_port_);
if (!accept_connections())
{
std::cerr << "Failure during call to accept." << std::endl;
}
}
else
{
std::cerr << "Error: " << error.message() << std::endl;
}
}
boost::asio::io_service& io_service_;
ip::address_v4 localhost_address;
ip::tcp::acceptor acceptor_;
ptr_type session_;
unsigned short upstream_port_;
std::string upstream_host_;
};
};
}
void push_regex(char* arg, vector<pair<string,boost::regex>> &v){
size_t expr_len = (strlen(arg)-1)/2;
char expr[expr_len];
unhexlify(arg+1, arg+strlen(arg)-1, expr);
boost::regex regex(reinterpret_cast<char*>(expr),
reinterpret_cast<char*>(expr) + expr_len);
v.push_back(make_pair(string(arg), regex));
}
int main(int argc, char* argv[])
{
if (argc < 5)
{
std::cerr << "usage: tcpproxy_server <local host ip> <local port> <forward host ip> <forward port> C..... S....." << std::endl;
return 1;
}
const unsigned short local_port = static_cast<unsigned short>(::atoi(argv[2]));
const unsigned short forward_port = static_cast<unsigned short>(::atoi(argv[4]));
const std::string local_host = argv[1];
const std::string forward_host = argv[3];
for (int i=5;i<argc;i++){
if (strlen(argv[i]) >= 1){
switch(argv[i][0]){
case 'C': { // Client to server Blacklist
push_regex(argv[i], regex_c_s_b);
break;
}
case 'c': { // Client to server Whitelist
push_regex(argv[i], regex_c_s_w);
break;
}
case 'S': { // Server to client Blacklist
push_regex(argv[i], regex_s_c_b);
break;
}
case 's': { // Server to client Whitelist
push_regex(argv[i], regex_s_c_w);
break;
}
}
}
}
boost::asio::io_service ios;
try
{
tcp_proxy::bridge::acceptor acceptor(ios,
local_host, local_port,
forward_host, forward_port);
acceptor.accept_connections();
ios.run();
}
catch(std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
/*
* [Note] On posix systems the tcp proxy server build command is as follows:
* c++ -pedantic -ansi -Wall -Werror -O3 -o tcpproxy_server tcpproxy_server.cpp -L/usr/lib -lstdc++ -lpthread -lboost_thread -lboost_system
*/

87
backend/c_back/proxy_wrap.py Executable file
View File

@@ -0,0 +1,87 @@
import subprocess, re
#c++ -o proxy proxy.cpp
class Filter:
def __init__(self, regex, is_blacklist=True, c_to_s=False, s_to_c=False ):
self.regex = regex
self.is_blacklist = is_blacklist
if c_to_s == s_to_c: c_to_s = s_to_c = True # (False, False) == (True, True)
self.c_to_s = c_to_s
self.s_to_c = s_to_c
self.blocked = 0
def compile(self):
if isinstance(self.regex, str): self.regex = self.regex.encode()
if not isinstance(self.regex, bytes): raise Exception("Invalid Regex Paramether")
re.compile(self.regex) # raise re.error if is invalid!
if self.c_to_s:
yield "C"+self.regex.hex() if self.is_blacklist else "c"+self.regex.hex()
if self.s_to_c:
yield "S"+self.regex.hex() if self.is_blacklist else "s"+self.regex.hex()
class Proxy:
def __init__(self, internal_port, public_port, filters=None, public_host="0.0.0.0", internal_host="127.0.0.1"):
self.public_host = public_host
self.public_port = public_port
self.internal_host = internal_host
self.internal_port = internal_port
self.filters = set(filters) if filters else set([])
self.process = None
def start(self, callback=None):
if self.process is None:
filter_map = self.compile_filters()
filters_codes = list(filter_map.keys())
self.process = subprocess.Popen(
["./proxy", str(self.public_host), str(self.public_port), str(self.internal_host), str(self.internal_port), *filters_codes],
stdout=subprocess.PIPE, universal_newlines=True
)
for stdout_line in iter(self.process.stdout.readline, ""):
if stdout_line.startswith("BLOCKED"):
regex_id = stdout_line.split()[1]
filter_map[regex_id].blocked+=1
if callback: callback(filter_map[regex_id])
self.process.stdout.close()
return self.process.wait()
def stop(self):
if self.process:
self.process.terminate()
try:
self.process.wait(timeout=3)
return True
except Exception:
self.process.kill()
return False
finally:
self.process = None
return True
def restart(self):
status = self.stop()
self.start()
return status
def reload(self):
if self.process: self.restart()
def compile_filters(self):
res = {}
for filter_obj in self.filters:
raw_filters = filter_obj.compile()
for filter in raw_filters:
res[filter] = filter_obj
return res
def add_filter(self, filter):
self.filters.add(filter)
self.reload()
def remove_filter(self, filter):
try:
del self.filters[self.filters.remove(filter)]
except ValueError: return
self.reload()

27
backend/nginx.conf Executable file
View File

@@ -0,0 +1,27 @@
worker_processes 5; ## Default: 1
pid /var/run/nginx.pid;
user nobody nobody;
events {
worker_connections 1024;
}
http{
server {
listen 80;
server_name _;
location / {
include proxy_params;
proxy_pass http://frontend:5000/;
}
location /api/ {
include proxy_params;
proxy_pass http://127.0.0.1:8080/;
}
}
}

2
backend/requirements.txt Executable file
View File

@@ -0,0 +1,2 @@
flask
uwsgi

29
backend/supervisord.conf Executable file
View File

@@ -0,0 +1,29 @@
[supervisord]
logfile = /dev/null
loglevel = info
user = root
pidfile = /var/run/supervisord.pid
nodaemon = true
[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"
autostart=true
autorestart=true
startretries=5
numprocs=1
startsecs=0
process_name=%(program_name)s_%(process_num)02d
stderr_logfile=/var/log/supervisor/%(program_name)s_stderr.log
stderr_logfile_maxbytes=10MB
stdout_logfile=/var/log/supervisor/%(program_name)s_stdout.log
stdout_logfile_maxbytes=10MB
[program:uwsgi_backend]
directory=/execute
command=uwsgi --http 127.0.0.1:8080 --master --module app:app
stdout_logfile="syslog"
stderr_logfile="syslog"
startsecs=10
stopsignal=QUIT
stopasgroup=true
killasgroup=true

0
docker-compose.yml Executable file
View File

28
frontend/.dockerignore Executable file
View File

@@ -0,0 +1,28 @@
Dockerfile
docker-compose.yml
**/*.pyc
**/__pycache__/
/.vscode/**
#Node filters
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

23
frontend/.gitignore vendored Executable file
View File

@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

14
frontend/Dockerfile Executable file
View File

@@ -0,0 +1,14 @@
FROM node:16-alpine
#React project copy
RUN apk add --update npm
RUN npm install -g npm@latest
RUN mkdir /app
WORKDIR /app
ADD package.json .
ADD package-lock.json .
RUN npm install
RUN npm install serve -g
COPY . .
RUN npm run build
ENTRYPOINT [ "serve", "-s", "build" ]

46
frontend/README.md Executable file
View File

@@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

29063
frontend/package-lock.json generated Executable file

File diff suppressed because it is too large Load Diff

53
frontend/package.json Executable file
View File

@@ -0,0 +1,53 @@
{
"name": "firegex-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@mantine/core": "^4.2.8",
"@mantine/form": "^4.2.8",
"@mantine/hooks": "^4.2.8",
"@mantine/modals": "^4.2.8",
"@mantine/notifications": "^4.2.8",
"@mantine/prism": "^4.2.8",
"@mantine/spotlight": "^4.2.8",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.39",
"@types/react": "^18.0.12",
"@types/react-dom": "^18.0.5",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-icons": "^4.4.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"sass": "^1.52.3",
"typescript": "^4.7.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
frontend/public/favicon.ico Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

43
frontend/public/index.html Executable file
View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
frontend/public/logo192.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
frontend/public/logo512.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

25
frontend/public/manifest.json Executable file
View File

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
frontend/public/robots.txt Executable file
View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

17
frontend/src/App.tsx Executable file
View File

@@ -0,0 +1,17 @@
import React from 'react';
import { Navigate, Route, Routes } from 'react-router-dom';
import MainLayout from './components/MainLayout';
import HomePage from './pages/HomePage';
import Service from './pages/Service';
function App() {
return <MainLayout>
<Routes>
<Route index element={<HomePage />} />
<Route path=":srv_id" element={<Service />} />
<Route path="*" element={<Navigate to="/" />} />
</Routes>
</MainLayout>
}
export default App;

2
frontend/src/_vars.scss Executable file
View File

@@ -0,0 +1,2 @@
$primary_color: #242a33;

View File

@@ -0,0 +1,9 @@
@use "../../vars" as *;
@use "../../index.scss" as *;
.footer{
height: 150px;
margin-top: 50px;
background-color: $primary_color;
@extend .center-flex;
}

View File

@@ -0,0 +1,12 @@
import React from 'react';
import style from "./Footer.module.scss";
function Footer() {
return <div id="footer" className={style.footer}>
Made by Pwnzer0tt1
</div>
}
export default Footer;

View File

@@ -0,0 +1,17 @@
@use "../../vars" as *;
.header{
width: 100%;
height: 140px;
background-color: $primary_color;
display: flex;
align-items: center;
justify-content: center;
}
.logo{
width: 200px;
margin-left: 40px;
height: 70%;
}

View File

@@ -0,0 +1,48 @@
import React, { useEffect, useState } from 'react';
import { ActionIcon, Badge } from '@mantine/core';
import style from "./Header.module.scss";
import { generalstats } from '../../js/utils';
import { GeneralStats, update_freq } from '../../js/models';
import { BsPlusLg } from "react-icons/bs"
import { AiFillHome } from "react-icons/ai"
import { useLocation, useNavigate } from 'react-router-dom';
function Header() {
const [generalStats, setGeneralStats] = useState<GeneralStats>({closed:0, regex:0, services:0});
const location = useLocation()
const navigator = useNavigate()
const updateInfo = () => {
generalstats().then(res => {
setGeneralStats(res)
setTimeout(updateInfo, update_freq)
}).catch(
err =>{
setTimeout(updateInfo, update_freq)}
)
}
useEffect(updateInfo,[]);
return <div id="header-page" className={style.header}>
<div className={style.logo} >LOGO</div>
<div className="flex-spacer" />
<Badge color="green" size="lg" variant="filled">Services: {generalStats.services}</Badge>
<Badge style={{marginLeft:"10px"}} size="lg" color="yellow" variant="filled">Filtered Connections: {generalStats.closed}</Badge>
<Badge style={{marginLeft:"10px"}} size="lg" color="violet" variant="filled">Regexes: {generalStats.regex}</Badge>
<div style={{marginLeft:"20px"}}></div>
{ location.pathname !== "/"?
<ActionIcon color="teal" style={{marginRight:"10px"}}
size="xl" radius="md" variant="filled"
onClick={()=>navigator("/")}>
<AiFillHome size="25px" />
</ActionIcon>
:null}
<ActionIcon color="blue" size="xl" radius="md" variant="filled"><BsPlusLg size="20px" /></ActionIcon>
<div style={{marginLeft:"40px"}}></div>
</div>
}
export default Header;

View File

@@ -0,0 +1,38 @@
import { Container, MantineProvider } from '@mantine/core';
import React, { useEffect, useState } from 'react';
import { Service, update_freq } from '../js/models';
import { servicelist } from '../js/utils';
import Footer from './Footer';
import Header from './Header';
function MainLayout({ children }:{ children:any }) {
const [services, setServices] = useState<Service[]>([]);
const updateInfo = () => {
servicelist().then(res => {
setServices(res)
setTimeout(updateInfo, update_freq)
}).catch(
err =>{
setTimeout(updateInfo, update_freq)}
)
}
useEffect(updateInfo,[]);
return <>
<MantineProvider theme={{ colorScheme: 'dark' }} withGlobalStyles withNormalizeCSS>
<Header />
<div style={{marginTop:"50px"}}/>
<Container size="xl" style={{minHeight:"58vh"}}>
{children}
</Container>
<div style={{marginTop:"50px"}}/>
<Footer />
</MantineProvider>
</>
}
export default MainLayout;

View File

@@ -0,0 +1,17 @@
@use "../../index.scss" as *;
.row{
width: 95%;
padding: 30px 0px;
border-radius: 20px;
margin: 10px;
@extend .center-flex;
}
.name{
font-size: 2.3em;
font-weight: bolder;
margin-right: 10px;
margin-bottom: 13px;
}

View File

@@ -0,0 +1,48 @@
import { ActionIcon, Badge, Grid, Space, Title } from '@mantine/core';
import React from 'react';
import { FaPause, FaPlay } from 'react-icons/fa';
import { Service } from '../../js/models';
import { MdOutlineArrowForwardIos } from "react-icons/md"
import style from "./ServiceRow.module.scss";
//"status":"stop"/"wait"/"active"/"pause",
function ServiceRow({ service, onClick }:{ service:Service, onClick?:()=>void }) {
let status_color = "gray";
switch(service.status){
case "stop": status_color = "red"; break;
case "wait": status_color = "yellow"; break;
case "active": status_color = "teal"; break;
case "pause": status_color = "cyan"; break;
}
return <>
<Grid className={style.row} style={{width:"100%"}}>
<Grid.Col span={4}>
<div className="center-flex-row">
<div className="center-flex"><Title className={style.name}>{service.name}</Title> <Badge size="xl" variant="filled">:{service.public_port}</Badge></div>
<Badge color={status_color} size="xl" radius="md">{service.internal_port} {"->"} {service.public_port}</Badge>
</div>
</Grid.Col>
<Grid.Col className="center-flex" span={8}>
<div className='flex-spacer'></div>
<div className="center-flex-row">
<Badge style={{marginBottom:"20px"}} color={status_color} radius="sm" size="xl" variant="filled">Status: <u>{service.status}</u></Badge>
<Badge style={{marginBottom:"8px"}}color="violet" radius="sm" size="lg" variant="filled">Regex: {service.n_regex}</Badge>
<Badge color="yellow" radius="sm" size="lg" variant="filled">Connections Blocked: {service.n_packets}</Badge>
</div>
<Space w="xl" /><Space w="xl" />
<div className="center-flex">
<ActionIcon color="red" size="xl" radius="md" variant="filled" disabled={!["wait","active"].includes(service.status)?true:false}><FaPause size="20px" /></ActionIcon>
<Space w="md"/>
<ActionIcon color="teal" size="xl" radius="md" variant="filled" disabled={!["stop","pause"].includes(service.status)?true:false}><FaPlay size="20px" /></ActionIcon>
</div>
<Space w="xl" /><Space w="xl" />
{onClick?<MdOutlineArrowForwardIos onClick={onClick} style={{cursor:"pointer"}} size="45px" />:null}
<Space w="xl" />
</Grid.Col>
</Grid>
<hr style={{width:"100%"}}/>
</>
}
export default ServiceRow;

24
frontend/src/index.scss Executable file
View File

@@ -0,0 +1,24 @@
@use "vars" as *;
@import url('https://fonts.googleapis.com/css2?family=Lato&display=swap');
body {
margin: 0;
font-family: 'Lato', sans-serif;
}
.center-flex{
display: flex;
justify-content: center;
align-items: center;
}
.center-flex-row{
@extend .center-flex;
flex-direction: column;
}
.flex-spacer{
flex-grow: 1;
}

22
frontend/src/index.tsx Executable file
View File

@@ -0,0 +1,22 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from "react-router-dom"
import './index.scss';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

19
frontend/src/js/models.ts Executable file
View File

@@ -0,0 +1,19 @@
export const update_freq = 3000;
export type GeneralStats = {
services:number,
closed:number,
regex:number
}
export type Service = {
id:string,
name:string,
status:string,
public_port:number,
internal_port:number,
n_packets:number,
n_regex:number,
}

14
frontend/src/js/utils.ts Executable file
View File

@@ -0,0 +1,14 @@
import { GeneralStats, Service } from "./models";
export async function getapi(path:string):Promise<any>{
return await fetch(`/api/${path}`).then( res => res.json() )
}
export async function generalstats():Promise<GeneralStats>{
return await getapi("general-stats") as GeneralStats;
}
export async function servicelist():Promise<Service[]>{
return await getapi("services") as Service[];
}

51
frontend/src/pages/HomePage.tsx Executable file
View File

@@ -0,0 +1,51 @@
import React, { useEffect, useState } from 'react';
import { Navigate, useNavigate, useRoutes } from 'react-router-dom';
import ServiceRow from '../components/ServiceRow';
import { Service, update_freq } from '../js/models';
import { servicelist } from '../js/utils';
function HomePage() {
const [services, setServices] = useState<Service[]>([
{
id:"ctfe",
internal_port:18080,
n_packets: 30,
n_regex: 40,
name:"CTFe",
public_port:80,
status:"pause"
},
{
id:"saas",
internal_port:18080,
n_packets: 30,
n_regex: 40,
name:"SaaS",
public_port:5000,
status:"active"
}
]);
const navigator = useNavigate()
const updateInfo = () => {
servicelist().then(res => {
setServices(res)
setTimeout(updateInfo, update_freq)
}).catch(
err =>{
setTimeout(updateInfo, update_freq)}
)
}
useEffect(updateInfo,[]);
return <div id="service-list" className="center-flex-row">
{services.map( srv => <ServiceRow service={srv} key={srv.id} onClick={()=>{
navigator("/"+srv.id)
}} />)}
</div>
}
export default HomePage;

11
frontend/src/pages/Service.tsx Executable file
View File

@@ -0,0 +1,11 @@
import React from 'react';
import { useParams } from 'react-router-dom';
function Service() {
const {srv_id} = useParams()
return <div>
Service: {srv_id}
</div>
}
export default Service;

1
frontend/src/react-app-env.d.ts vendored Executable file
View File

@@ -0,0 +1 @@
/// <reference types="react-scripts" />

15
frontend/src/reportWebVitals.ts Executable file
View File

@@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

5
frontend/src/setupTests.ts Executable file
View File

@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

26
frontend/tsconfig.json Executable file
View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}