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

Deployment on bastion #28

Merged
merged 4 commits into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
85 changes: 28 additions & 57 deletions build.sh
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,66 +1,37 @@
#! /bin/bash
#!/bin/bash

sudo git clone https://github.com/alegarsan11/nftables-gui.git /var/www/flask
# Configuración de Matplotlib
export MPLCONFIGDIR=/tmp/matplotlib
sudo mkdir -p $MPLCONFIGDIR
sudo chown www-data:www-data $MPLCONFIGDIR
sudo chmod 777 $MPLCONFIGDIR

# Variables
PROJECT_DIR=/var/www/flask/nftables-frontend
PROJECT_NAME=nftables-gui
WSGI_FILE=wsgi.py
VENV_DIR=$PROJECT_DIR/venv
PYTHON_VERSION=python3.8
# Instalación de dependencias
sudo apt-get install -y libfreetype6-dev libxft-dev

# Actualizar los repositorios de paquetes
sudo apt update
# Copiar la aplicación
sudo cp -r nftables-frontend /usr/share

# Instalar Apache y el módulo mod_wsgi para Python 3 si no están instalados
sudo apt install -y apache2 libapache2-mod-wsgi-py3

# Crear un archivo WSGI para que Apache pueda interactuar con la aplicación Flask
cat <<EOT > $PROJECT_DIR/$WSGI_FILE
import sys
import logging

# Configurar el logging
logging.basicConfig(stream=sys.stderr)

# Añadir el directorio del proyecto al path
sys.path.insert(0, "$PROJECT_DIR")

from app import app as application # Ajusta según tu archivo principal de Flask
EOT

# Configurar Apache para servir la aplicación Flask
sudo tee /etc/apache2/sites-available/$PROJECT_NAME.conf > /dev/null <<EOT
<VirtualHost *:80>
ServerName localhost

WSGIDaemonProcess $PROJECT_NAME python-path=$VENV_DIR/lib/$PYTHON_VERSION/site-packages
WSGIScriptAlias / $PROJECT_DIR/$WSGI_FILE

<Directory $PROJECT_DIR>
Require all granted
</Directory>

Alias /static $PROJECT_DIR/static
<Directory $PROJECT_DIR/static/>
Require all granted
</Directory>

ErrorLog \${APACHE_LOG_DIR}/$PROJECT_NAME_error.log
CustomLog \${APACHE_LOG_DIR}/$PROJECT_NAME_access.log combined
</VirtualHost>
EOT
# Instalación y configuración de Apache con WSGI
sudo apt-get install -y libapache2-mod-wsgi-py3
sudo a2enmod wsgi

# Actualizar los repositorios de paquetes
sudo apt update
# Configuración del sitio de Apache
sudo cp nftables-frontend/nftables-config.conf /etc/apache2/sites-available/nftables-config.conf
sudo a2ensite nftables-config.conf

# Instalar Apache y el módulo mod_wsgi para Python 3 si no están instalados
sudo apt install -y apache2 libapache2-mod-wsgi-py3
# Ajuste de permisos
sudo chmod 664 /usr/share/nftables-frontend/instance/nftables.db
sudo chown www-data:www-data /usr/share/nftables-frontend/instance/nftables.db
sudo chown -R www-data:www-data /usr/share/nftables-frontend
sudo chmod -R 775 /usr/share/nftables-frontend
sudo chmod -R 775 /usr/share/nftables-frontend/instance
sudo chmod -R 775 /usr/share/nftables-frontend/static
sudo chown -R www-data:www-data /usr/share/nftables-frontend/static

# Habilitar el sitio y el módulo wsgi
sudo a2ensite $PROJECT_NAME.conf
sudo a2enmod wsgi
#Reiniciar Apache para aplicar los cambios
# Reiniciar Apache
sudo systemctl restart apache2

echo "La aplicación Flask ahora debería estar disponible en http://localhost"
# Iniciar el parser de nftables
cd nftables-parser
sudo hug -f main.py
37 changes: 34 additions & 3 deletions nftables-frontend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,38 @@
import os
from service import create_default_user, login_manager

ERROR = 'error.html'

app = Flask(__name__)
app.register_blueprint(visualization_bp)
app.register_blueprint(creation_bp)
dir_path = os.path.dirname(os.path.realpath(__file__))
app.config['SECRET_KEY'] = 'hfds732klejds90ahg'
Dismissed Show dismissed Hide dismissed
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{dir_path}/instance/nftables.db'
app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
app.config['SESSION_COOKIE_SECURE'] = True
login_manager.init_app(app)
db.init_app(app)

with app.app_context():
db.create_all()
create_default_user()

migrate = Migrate(app, db)
Bootstrap(app)

@app.errorhandler(404)
def page_not_found(e):
return render_template(ERROR, message='Page not found'), 404

@app.errorhandler(500)
def internal_error(e):
return render_template(ERROR, message="Internal server error"), 500

@app.route('/favicon.ico')
def favicon():
return app.send_static_file('favicon.ico')

def create_app():
app = Flask(__name__)
app.register_blueprint(visualization_bp)
Expand All @@ -27,11 +59,11 @@ def create_app():

@app.errorhandler(404)
def page_not_found(e):
return render_template('error.html', message='Page not found'), 404
return render_template(ERROR, message='Page not found'), 404

@app.errorhandler(500)
def internal_error(e):
return render_template('error.html', message="Internal server error"), 500
return render_template(ERROR, message="Internal server error"), 500

@app.route('/favicon.ico')
def favicon():
Expand All @@ -40,5 +72,4 @@ def favicon():
return app

if __name__ == '__main__':
app = create_app()
app.run(debug=False)
Binary file added nftables-frontend/instance/nftables.db
Binary file not shown.
24 changes: 24 additions & 0 deletions nftables-frontend/nftables-config.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
DocumentRoot /usr/share/nftables-frontend
WSGIDaemonProcess nftables-frontend user=www-data group=www-data threads=5
WSGIScriptAlias / /usr/share/nftables-frontend/run.wsgi
<Directory /usr/share/nftables-frontend>
WSGIProcessGroup nftables-frontend
WSGIApplicationGroup %{GLOBAL}
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
Alias /static /usr/share/nftables-frontend/static
<Directory /usr/share/nftables-frontend/static>
Require all granted
</Directory>
Alias /templates /usr/share/nftables-frontend/templates
<Directory /usr/share/nftables-frontend/templates>
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
13 changes: 13 additions & 0 deletions nftables-frontend/run.wsgi
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import os
import sys
import matplotlib
matplotlib.use('Agg') # Configurar el backend de Matplotlib

# Establece la variable de entorno MPLCONFIGDIR
os.environ['MPLCONFIGDIR'] = '/tmp/matplotlib'

# Añade tu aplicación al path de Python
sys.path.insert(0,'/usr/share/nftables-frontend')

# Importa tu aplicación
from app import app as application
Binary file added nftables-frontend/static/img/nftables_info.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion nftables-frontend/templates/chains/chains.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ <h1>Chains:</h1>
<td>{{ chain.policy }}</td>
{% endif %}
<td>
<a href="/chains/{{ chain.name }}/{{ chain.family }}/{{chain.table.id}}/delete" class="btn btn-danger">Delete</a>
<a href="/chains/{{ chain.id }}/{{chain.table.id}}/delete" class="btn btn-danger">Delete</a>
</td>
</tr>
{% endfor %}
Expand Down
8 changes: 6 additions & 2 deletions nftables-frontend/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ def main_view():
categories = ['Rules', 'Chains', 'Tables']
# Get the number of rules, chains and tables
values = service.load_data(False)
image_path = 'static/img/nftables_info.png'
# Obtén la ruta del directorio actual
dir_path = os.path.dirname(os.path.realpath(__file__))

# Construye la ruta absoluta al archivo
image_path = os.path.join(dir_path, 'static/img/nftables_info.png')
plt.figure(figsize=(8, 6))
plt.bar(categories, values, color=['blue', 'green', 'orange'])
plt.xlabel('nftables elements')
Expand Down Expand Up @@ -605,7 +609,7 @@ def add_list_post():
form = AddListForm()
lista = request.files['list'].read().decode('utf-8').split("\n")
form.element.data = lista
if 'txt' not in request.files['list'].filename:
if '.txt' not in request.files['list'].filename:

flash('Error adding list.')
tables = service.get_tables()
Expand Down
Loading