Compare commits
No commits in common. "master" and "v1.0.0" have entirely different histories.
155
README.md
155
README.md
@ -1,155 +0,0 @@
|
|||||||
# CBS CyberScan - Escaner Web Antivirus
|
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<img src="https://condorbs.net/favicon.ico" alt="CBS Logo" width="50"/>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
## Descripción
|
|
||||||
CBS CyberScan es una aplicación web que proporciona un servicio de escaneo de archivos y URLs en tiempo real. Utiliza ClamAV como motor de análisis antivirus y ofrece una interfaz moderna y cibernética para una experiencia de usuario mejorada.
|
|
||||||
|
|
||||||
## Características Principales
|
|
||||||
- 🔍 Escaneo de archivos locales
|
|
||||||
- 🌐 Análisis de archivos desde URLs
|
|
||||||
- 🔄 Verificación de hashes (MD5, SHA1, SHA256)
|
|
||||||
- 💾 Almacenamiento de resultados en base de datos
|
|
||||||
- ⚡ Interfaz en tiempo real con WebSockets
|
|
||||||
- 📊 Estadísticas detalladas de escaneo
|
|
||||||
- 🎯 Detección y conteo de amenazas
|
|
||||||
|
|
||||||
## Requisitos del Sistema
|
|
||||||
- Python 3.8+
|
|
||||||
- MySQL/MariaDB
|
|
||||||
- ClamAV
|
|
||||||
- Navegador web moderno
|
|
||||||
|
|
||||||
## Dependencias Principales
|
|
||||||
```plaintext
|
|
||||||
Flask==3.0.2
|
|
||||||
flask-socketio==5.3.6
|
|
||||||
python-dotenv==1.0.1
|
|
||||||
mysql-connector-python==8.3.0
|
|
||||||
filetype==1.2.0
|
|
||||||
requests==2.31.0
|
|
||||||
```
|
|
||||||
|
|
||||||
## Instalación
|
|
||||||
|
|
||||||
1. Clonar el repositorio:
|
|
||||||
```bash
|
|
||||||
git clone https://condorcs.net/mrhacker/cbs-web-antivirus-scanner.git
|
|
||||||
cd cbs-web-antivirus-scanner
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Crear y activar entorno virtual:
|
|
||||||
```bash
|
|
||||||
python -m venv venv
|
|
||||||
|
|
||||||
# En Linux/Mac:
|
|
||||||
source venv/bin/activate
|
|
||||||
|
|
||||||
# En Windows:
|
|
||||||
.\venv\Scripts\activate
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Instalar dependencias:
|
|
||||||
```bash
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
4. Configurar la base de datos:
|
|
||||||
```sql
|
|
||||||
CREATE DATABASE cbswebscan;
|
|
||||||
USE cbswebscan;
|
|
||||||
|
|
||||||
CREATE TABLE file_scans (
|
|
||||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
||||||
filename VARCHAR(255),
|
|
||||||
md5_hash VARCHAR(32),
|
|
||||||
sha1_hash VARCHAR(40),
|
|
||||||
sha256_hash VARCHAR(64),
|
|
||||||
file_type VARCHAR(50),
|
|
||||||
scan_result TEXT,
|
|
||||||
scan_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
||||||
);
|
|
||||||
```
|
|
||||||
|
|
||||||
5. Configurar variables de entorno:
|
|
||||||
Crear archivo `.env`:
|
|
||||||
```plaintext
|
|
||||||
DB_HOST=localhost
|
|
||||||
DB_USER=your_username
|
|
||||||
DB_PASSWD=your_password
|
|
||||||
DB_NAME=cbswebscan
|
|
||||||
DB_CHARSET=utf8mb4
|
|
||||||
DB_COALLITION=utf8mb4_unicode_ci
|
|
||||||
```
|
|
||||||
|
|
||||||
## Uso
|
|
||||||
|
|
||||||
1. Iniciar el servidor:
|
|
||||||
```bash
|
|
||||||
python app.py
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Acceder a la aplicación:
|
|
||||||
Abrir en el navegador: `http://localhost:5000`
|
|
||||||
|
|
||||||
## Historial de Versiones
|
|
||||||
|
|
||||||
### v2.0.0 (Actual)
|
|
||||||

|
|
||||||
- Interfaz completamente rediseñada con estilo cibernético
|
|
||||||
- Sistema de escritura tipo terminal
|
|
||||||
- Panel de estadísticas en tiempo real
|
|
||||||
- Efectos visuales y animaciones mejoradas
|
|
||||||
- Mejor manejo de amenazas y resultados
|
|
||||||
|
|
||||||
### v1.0.0
|
|
||||||

|
|
||||||
- Primera versión estable
|
|
||||||
- Funcionalidades básicas de escaneo
|
|
||||||
- Interfaz simple y funcional
|
|
||||||
|
|
||||||
## Estructura del Proyecto
|
|
||||||
```plaintext
|
|
||||||
cbs-cyberscan/
|
|
||||||
├── app.py # Aplicación principal
|
|
||||||
├── requirements.txt # Dependencias del proyecto
|
|
||||||
├── .env # Variables de entorno
|
|
||||||
├── static/ # Archivos estáticos
|
|
||||||
├── templates/ # Plantillas HTML
|
|
||||||
│ └── index.html # Interfaz principal
|
|
||||||
└── README.md # Documentación
|
|
||||||
```
|
|
||||||
|
|
||||||
## Seguridad
|
|
||||||
- Los archivos se escanean en un entorno aislado
|
|
||||||
- Verificación de hashes para evitar escaneos duplicados
|
|
||||||
- Limpieza automática de archivos temporales
|
|
||||||
- Validación de tipos de archivo y URLs
|
|
||||||
|
|
||||||
## Contribuir
|
|
||||||
1. Fork del repositorio
|
|
||||||
2. Crear rama para nueva característica (`git checkout -b feature/nueva-caracteristica`)
|
|
||||||
3. Commit de cambios (`git commit -am 'Agregar nueva característica'`)
|
|
||||||
4. Push a la rama (`git push origin feature/nueva-caracteristica`)
|
|
||||||
5. Crear Pull Request
|
|
||||||
|
|
||||||
## Screenshots
|
|
||||||
|
|
||||||
Para agregar capturas de pantalla de nuevas versiones:
|
|
||||||
1. Crear carpeta `screenshots` si no existe
|
|
||||||
2. Nombrar las imágenes siguiendo el formato `vX.X.X.png`
|
|
||||||
3. Actualizar la sección "Historial de Versiones" de este README
|
|
||||||
|
|
||||||
|
|
||||||
## Autores
|
|
||||||
- Kevin Muñoz
|
|
||||||
|
|
||||||
## Soporte
|
|
||||||
Para reportar problemas o solicitar ayuda:
|
|
||||||
- Crear un issue en GitHub
|
|
||||||
- Contactar a helpdesk@condorbs.net
|
|
||||||
|
|
||||||
---
|
|
||||||
Desarrollado con ❤️ por Kevin Muñoz
|
|
395
app.py
395
app.py
@ -8,319 +8,184 @@ import requests
|
|||||||
import hashlib
|
import hashlib
|
||||||
import mysql.connector
|
import mysql.connector
|
||||||
import filetype
|
import filetype
|
||||||
from urllib.parse import urlparse
|
|
||||||
from pathlib import Path
|
|
||||||
import logging
|
|
||||||
|
|
||||||
# Cargar variables de entorno al inicio
|
|
||||||
load_dotenv()
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
socketio = SocketIO(app, cors_allowed_origins="*")
|
socketio = SocketIO(app)
|
||||||
|
|
||||||
# Configuración de logging
|
|
||||||
logging.basicConfig(
|
|
||||||
level=logging.DEBUG,
|
|
||||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
||||||
)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# Configuración de la base de datos
|
|
||||||
DB_CONFIG = {
|
|
||||||
'host': os.getenv('DB_HOST'),
|
|
||||||
'user': os.getenv('DB_USER'),
|
|
||||||
'password': os.getenv('DB_PASSWD'),
|
|
||||||
'database': os.getenv('DB_NAME'),
|
|
||||||
'charset': os.getenv('DB_CHARSET'),
|
|
||||||
'collation': os.getenv('DB_COALLITION')
|
|
||||||
}
|
|
||||||
|
|
||||||
def get_db_connection():
|
|
||||||
"""Establece y retorna una conexión a la base de datos."""
|
|
||||||
try:
|
|
||||||
return mysql.connector.connect(**DB_CONFIG)
|
|
||||||
except mysql.connector.Error as err:
|
|
||||||
logger.error(f"Error connecting to database: {err}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
def get_file_hashes(file_path):
|
def get_file_hashes(file_path):
|
||||||
"""Calcula los hashes de un archivo."""
|
hash_md5 = hashlib.md5()
|
||||||
try:
|
hash_sha1 = hashlib.sha1()
|
||||||
hash_md5 = hashlib.md5()
|
hash_sha256 = hashlib.sha256()
|
||||||
hash_sha1 = hashlib.sha1()
|
|
||||||
hash_sha256 = hashlib.sha256()
|
|
||||||
|
|
||||||
with open(file_path, "rb") as f:
|
with open(file_path, "rb") as f:
|
||||||
for chunk in iter(lambda: f.read(4096), b""):
|
for chunk in iter(lambda: f.read(4096), b""):
|
||||||
hash_md5.update(chunk)
|
hash_md5.update(chunk)
|
||||||
hash_sha1.update(chunk)
|
hash_sha1.update(chunk)
|
||||||
hash_sha256.update(chunk)
|
hash_sha256.update(chunk)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"md5": hash_md5.hexdigest(),
|
"md5": hash_md5.hexdigest(),
|
||||||
"sha1": hash_sha1.hexdigest(),
|
"sha1": hash_sha1.hexdigest(),
|
||||||
"sha256": hash_sha256.hexdigest()
|
"sha256": hash_sha256.hexdigest()
|
||||||
}
|
}
|
||||||
except IOError as e:
|
|
||||||
logger.error(f"Error reading file for hashing: {e}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
def get_file_type(file_path):
|
def get_file_type(file_path):
|
||||||
"""Determina el tipo MIME del archivo."""
|
kind = filetype.guess(file_path)
|
||||||
try:
|
if kind is None:
|
||||||
kind = filetype.guess(file_path)
|
return "Unknown"
|
||||||
return kind.mime if kind else "application/octet-stream"
|
return kind.mime
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error determining file type: {e}")
|
|
||||||
return "application/octet-stream"
|
|
||||||
|
|
||||||
def check_file_in_db(hashes):
|
def check_file_in_db(hashes):
|
||||||
"""Verifica si el archivo ya existe en la base de datos."""
|
connection = mysql.connector.connect(
|
||||||
if not all(hashes.values()):
|
host=os.getenv('DB_HOST'),
|
||||||
return None
|
user=os.getenv('DB_USER'),
|
||||||
|
password=os.getenv('DB_PASSWD'),
|
||||||
try:
|
database=os.getenv('DB_NAME'),
|
||||||
connection = get_db_connection()
|
charset=os.getenv('DB_CHARSET'),
|
||||||
cursor = connection.cursor(dictionary=True)
|
collation=os.getenv('DB_COALLITION')
|
||||||
|
)
|
||||||
query = """
|
cursor = connection.cursor()
|
||||||
SELECT filename, file_type, scan_result,
|
|
||||||
DATE_FORMAT(scan_date, '%Y-%m-%d %H:%i:%s') as scan_date,
|
|
||||||
md5_hash, sha1_hash, sha256_hash
|
|
||||||
FROM file_scans
|
|
||||||
WHERE md5_hash = %(md5)s
|
|
||||||
OR sha1_hash = %(sha1)s
|
|
||||||
OR sha256_hash = %(sha256)s
|
|
||||||
LIMIT 1
|
|
||||||
"""
|
|
||||||
cursor.execute(query, {
|
|
||||||
'md5': hashes['md5'],
|
|
||||||
'sha1': hashes['sha1'],
|
|
||||||
'sha256': hashes['sha256']
|
|
||||||
})
|
|
||||||
|
|
||||||
result = cursor.fetchone()
|
|
||||||
cursor.close()
|
|
||||||
connection.close()
|
|
||||||
|
|
||||||
return result
|
query = "SELECT scan_result FROM file_scans WHERE md5_hash = %s OR sha1_hash = %s OR sha256_hash = %s"
|
||||||
|
cursor.execute(query, (hashes["md5"], hashes["sha1"], hashes["sha256"]))
|
||||||
except mysql.connector.Error as err:
|
result = cursor.fetchone()
|
||||||
logger.error(f"Database error: {err}")
|
|
||||||
raise
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
def store_file_in_db(filename, hashes, file_type, scan_result):
|
def store_file_in_db(filename, hashes, file_type, scan_result):
|
||||||
"""Almacena los resultados del escaneo en la base de datos."""
|
connection = mysql.connector.connect(
|
||||||
if not all([filename, hashes, file_type, scan_result]):
|
host=os.getenv('DB_HOST'),
|
||||||
raise ValueError("Missing required parameters for database storage")
|
user=os.getenv('DB_USER'),
|
||||||
|
password=os.getenv('DB_PASSWD'),
|
||||||
try:
|
database=os.getenv('DB_NAME'),
|
||||||
connection = get_db_connection()
|
charset=os.getenv('DB_CHARSET'),
|
||||||
cursor = connection.cursor()
|
collation=os.getenv('DB_COALLITION')
|
||||||
|
)
|
||||||
query = """
|
cursor = connection.cursor()
|
||||||
INSERT INTO file_scans
|
|
||||||
(filename, md5_hash, sha1_hash, sha256_hash, file_type, scan_result)
|
|
||||||
VALUES (%(filename)s, %(md5)s, %(sha1)s, %(sha256)s, %(file_type)s, %(scan_result)s)
|
|
||||||
"""
|
|
||||||
|
|
||||||
cursor.execute(query, {
|
|
||||||
'filename': filename,
|
|
||||||
'md5': hashes['md5'],
|
|
||||||
'sha1': hashes['sha1'],
|
|
||||||
'sha256': hashes['sha256'],
|
|
||||||
'file_type': file_type,
|
|
||||||
'scan_result': scan_result
|
|
||||||
})
|
|
||||||
|
|
||||||
connection.commit()
|
|
||||||
cursor.close()
|
|
||||||
connection.close()
|
|
||||||
|
|
||||||
except mysql.connector.Error as err:
|
|
||||||
logger.error(f"Error storing scan results: {err}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
@app.route('/')
|
query = """
|
||||||
|
INSERT INTO file_scans (filename, md5_hash, sha1_hash, sha256_hash, file_type, scan_result)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s)
|
||||||
|
"""
|
||||||
|
cursor.execute(query, (filename, hashes["md5"], hashes["sha1"], hashes["sha256"], file_type, scan_result))
|
||||||
|
connection.commit()
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
@app.route('/', methods=['GET', 'POST'])
|
||||||
def index():
|
def index():
|
||||||
return render_template('index.html')
|
return render_template('index.html')
|
||||||
|
|
||||||
@app.route('/upload', methods=['POST'])
|
@app.route('/upload', methods=['POST'])
|
||||||
def upload_file():
|
def upload_file():
|
||||||
"""Maneja la subida y escaneo de archivos."""
|
file = request.files.get('file')
|
||||||
try:
|
if file:
|
||||||
if 'file' not in request.files:
|
file_path = os.path.join('/tmp', f"{uuid.uuid4()}_{file.filename}")
|
||||||
return jsonify({'error': 'No se recibió ningún archivo'}), 400
|
file.save(file_path)
|
||||||
|
|
||||||
file = request.files['file']
|
|
||||||
if not file.filename:
|
|
||||||
return jsonify({'error': 'Nombre de archivo vacío'}), 400
|
|
||||||
|
|
||||||
# Guardar archivo temporalmente y calcular hashes
|
# Obtener los hashes y el tipo de archivo
|
||||||
temp_path = Path('/tmp') / f"{uuid.uuid4()}_{file.filename}"
|
hashes = get_file_hashes(file_path)
|
||||||
file.save(str(temp_path))
|
file_type = get_file_type(file_path)
|
||||||
|
|
||||||
# Calcular hashes y tipo de archivo
|
# Verificar si el archivo ya fue escaneado
|
||||||
hashes = get_file_hashes(str(temp_path))
|
|
||||||
file_type = get_file_type(str(temp_path))
|
|
||||||
|
|
||||||
# Verificar si existe en la base de datos
|
|
||||||
existing_result = check_file_in_db(hashes)
|
existing_result = check_file_in_db(hashes)
|
||||||
|
|
||||||
if existing_result:
|
if existing_result:
|
||||||
# Si existe, eliminar archivo temporal y devolver resultado existente
|
os.remove(file_path)
|
||||||
temp_path.unlink()
|
# Formatear el resultado del escaneo para que sea más legible
|
||||||
|
scan_result = format_scan_result(existing_result[0])
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'message': 'Yo a este lo conozco',
|
'message': 'Este archivo ya lo he visto antes.',
|
||||||
'result': {
|
'scan_result': scan_result
|
||||||
'filename': existing_result['filename'],
|
|
||||||
'file_type': existing_result['file_type'],
|
|
||||||
'scan_date': existing_result['scan_date'],
|
|
||||||
'scan_result': existing_result['scan_result'],
|
|
||||||
'hashes': {
|
|
||||||
'md5': existing_result['md5_hash'],
|
|
||||||
'sha1': existing_result['sha1_hash'],
|
|
||||||
'sha256': existing_result['sha256_hash']
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
# Si no existe, iniciar escaneo
|
# Ejecuta el escaneo en un hilo separado para no bloquear la aplicación
|
||||||
socketio.start_background_task(
|
socketio.start_background_task(target=scan_file, file_path=file_path, hashes=hashes, file_type=file_type, filename=file.filename)
|
||||||
target=scan_file,
|
|
||||||
file_path=str(temp_path),
|
|
||||||
hashes=hashes,
|
|
||||||
file_type=file_type,
|
|
||||||
filename=file.filename
|
|
||||||
)
|
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({'message': 'Archivo subido exitosamente: ' + file.filename})
|
||||||
'message': f'Archivo {file.filename} subido exitosamente. Iniciando escaneo...',
|
return jsonify({'error': 'No se recibió ningún archivo'}), 400
|
||||||
'hashes': hashes
|
|
||||||
})
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error in upload_file: {e}")
|
|
||||||
return jsonify({'error': str(e)}), 500
|
|
||||||
|
|
||||||
@app.route('/scan_url', methods=['POST'])
|
@app.route('/scan_url', methods=['POST'])
|
||||||
def scan_url():
|
def scan_url():
|
||||||
"""Maneja el escaneo de archivos desde URLs."""
|
url = request.json.get('url')
|
||||||
|
if not url:
|
||||||
|
return jsonify({'error': 'No URL provided'}), 400
|
||||||
|
|
||||||
|
# Añadir esquema si falta
|
||||||
|
if not url.startswith(('http://', 'https://')):
|
||||||
|
url = 'http://' + url
|
||||||
|
|
||||||
try:
|
try:
|
||||||
url = request.json.get('url')
|
# Descargar el contenido de la URL a un archivo temporal
|
||||||
if not url:
|
response = requests.get(url)
|
||||||
return jsonify({'error': 'URL no proporcionada'}), 400
|
if response.status_code != 200:
|
||||||
|
return jsonify({'error': f'Error al descargar la URL: {response.status_code}'}), 400
|
||||||
|
|
||||||
# Validar y normalizar URL
|
file_path = os.path.join('/tmp', f"{uuid.uuid4()}_downloaded_content")
|
||||||
parsed_url = urlparse(url if '://' in url else f'http://{url}')
|
with open(file_path, 'wb') as temp_file:
|
||||||
if not all([parsed_url.scheme, parsed_url.netloc]):
|
temp_file.write(response.content)
|
||||||
return jsonify({'error': 'URL inválida'}), 400
|
|
||||||
|
|
||||||
# Descargar archivo
|
# Obtener los hashes y el tipo de archivo
|
||||||
try:
|
hashes = get_file_hashes(file_path)
|
||||||
response = requests.get(parsed_url.geturl(), timeout=30)
|
file_type = get_file_type(file_path)
|
||||||
response.raise_for_status()
|
|
||||||
except requests.exceptions.RequestException as e:
|
|
||||||
return jsonify({'error': f'Error al descargar la URL: {str(e)}'}), 400
|
|
||||||
|
|
||||||
# Crear archivo temporal
|
|
||||||
file_path = Path('/tmp') / f"{uuid.uuid4()}_downloaded_content"
|
|
||||||
file_path.write_bytes(response.content)
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Calcular hashes y tipo de archivo
|
|
||||||
hashes = get_file_hashes(str(file_path))
|
|
||||||
file_type = get_file_type(str(file_path))
|
|
||||||
|
|
||||||
# Obtener nombre del archivo de la URL o usar uno genérico
|
|
||||||
filename = Path(parsed_url.path).name or "downloaded_file"
|
|
||||||
|
|
||||||
# Verificar si existe en la base de datos
|
|
||||||
existing_result = check_file_in_db(hashes)
|
|
||||||
|
|
||||||
if existing_result:
|
|
||||||
# Si existe, eliminar archivo temporal y devolver resultado existente
|
|
||||||
file_path.unlink()
|
|
||||||
return jsonify({
|
|
||||||
'message': 'Yo a este lo conozco',
|
|
||||||
'result': {
|
|
||||||
'filename': existing_result['filename'],
|
|
||||||
'file_type': existing_result['file_type'],
|
|
||||||
'scan_date': existing_result['scan_date'],
|
|
||||||
'scan_result': existing_result['scan_result'],
|
|
||||||
'hashes': {
|
|
||||||
'md5': existing_result['md5_hash'],
|
|
||||||
'sha1': existing_result['sha1_hash'],
|
|
||||||
'sha256': existing_result['sha256_hash']
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
# Si no existe, iniciar escaneo
|
|
||||||
socketio.start_background_task(
|
|
||||||
target=scan_file,
|
|
||||||
file_path=str(file_path),
|
|
||||||
hashes=hashes,
|
|
||||||
file_type=file_type,
|
|
||||||
filename=filename
|
|
||||||
)
|
|
||||||
|
|
||||||
|
# Verificar si el archivo ya fue escaneado
|
||||||
|
existing_result = check_file_in_db(hashes)
|
||||||
|
if existing_result:
|
||||||
|
os.remove(file_path)
|
||||||
|
# Formatear el resultado del escaneo para que sea más legible
|
||||||
|
scan_result = format_scan_result(existing_result[0])
|
||||||
return jsonify({
|
return jsonify({
|
||||||
'message': 'URL descargada. Iniciando análisis...',
|
'message': 'Este archivo ya lo he visto antes.',
|
||||||
'hashes': hashes
|
'scan_result': scan_result
|
||||||
})
|
})
|
||||||
|
|
||||||
except Exception as e:
|
# Ejecutar el escaneo en un hilo separado para no bloquear la aplicación
|
||||||
# Asegurar limpieza del archivo temporal en caso de error
|
socketio.start_background_task(target=scan_file, file_path=file_path, hashes=hashes, file_type=file_type, filename=filename)
|
||||||
if file_path.exists():
|
|
||||||
file_path.unlink()
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
return jsonify({'message': f'Archivo descargado y guardado como {file_path}. El escaneo está en progreso.'}), 200
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error in scan_url: {e}")
|
return jsonify({'error': str(e)}), 500
|
||||||
return jsonify({'error': 'Error interno del servidor'}), 500
|
|
||||||
|
|
||||||
def scan_file(file_path, hashes, file_type, filename):
|
def scan_file(file_path, hashes, file_type, filename):
|
||||||
"""Ejecuta el escaneo del archivo."""
|
|
||||||
try:
|
try:
|
||||||
# Ejecutar ClamAV
|
# Ejecuta el comando de escaneo
|
||||||
scan_command = ["clamscan", "-r", file_path]
|
scan_command = ["clamscan", "-r", file_path]
|
||||||
process = subprocess.run(
|
process = subprocess.Popen(scan_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
|
||||||
scan_command,
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
check=True,
|
|
||||||
timeout=300
|
|
||||||
)
|
|
||||||
|
|
||||||
# Procesar y emitir resultado línea por línea
|
# Lee la salida y los errores usando communicate()
|
||||||
scan_output = process.stdout
|
scan_output, error_output = process.communicate()
|
||||||
for line in scan_output.split('\n'):
|
|
||||||
if line.strip():
|
|
||||||
socketio.emit('scan_output', {'data': line + '\n'})
|
|
||||||
|
|
||||||
# Almacenar resultado en la base de datos
|
# Verificar el código de retorno del proceso
|
||||||
|
if process.returncode != 0:
|
||||||
|
socketio.emit('scan_output', {'data': f'Error en el escaneo: {error_output}'})
|
||||||
|
return
|
||||||
|
|
||||||
|
# Si no hubo errores, emitir la salida del escaneo
|
||||||
|
socketio.emit('scan_output', {'data': scan_output})
|
||||||
|
|
||||||
|
# Emitir mensaje de escaneo completo
|
||||||
|
socketio.emit('scan_output', {'data': '--- Escaneo completado ---'})
|
||||||
|
|
||||||
|
# Almacenar los hashes, el tipo de archivo y el resultado del escaneo en la base de datos
|
||||||
store_file_in_db(filename, hashes, file_type, scan_output)
|
store_file_in_db(filename, hashes, file_type, scan_output)
|
||||||
|
|
||||||
# Emitir mensaje de finalización
|
|
||||||
socketio.emit('scan_output', {'data': '\n--- Escaneo completado ---\n'})
|
|
||||||
|
|
||||||
except subprocess.TimeoutExpired:
|
|
||||||
socketio.emit('scan_output', {'data': 'Error: El escaneo excedió el tiempo límite\n'})
|
|
||||||
except subprocess.CalledProcessError as e:
|
|
||||||
socketio.emit('scan_output', {'data': f'Error en el escaneo: {e.stderr}\n'})
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
socketio.emit('scan_output', {'data': f'Error: {str(e)}\n'})
|
socketio.emit('scan_output', {'data': f'Error: {str(e)}'})
|
||||||
finally:
|
finally:
|
||||||
# Limpiar archivo temporal
|
# Asegúrate de eliminar el archivo temporal después del escaneo
|
||||||
try:
|
if os.path.exists(file_path):
|
||||||
Path(file_path).unlink(missing_ok=True)
|
os.remove(file_path)
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error removing temporary file: {e}")
|
def format_scan_result(scan_result):
|
||||||
|
# Formatear el resultado del escaneo para mejor legibilidad
|
||||||
|
formatted_result = scan_result.replace("\n", "<br>")
|
||||||
|
return formatted_result
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# Asegurarse de que el directorio temporal existe
|
socketio.run(app, host='0.0.0.0', port=5001, debug=os.getenv('FLASK_DEBUG', 'False').lower() == 'true')
|
||||||
Path('/tmp').mkdir(exist_ok=True)
|
|
||||||
|
|
||||||
# Iniciar la aplicación
|
|
||||||
socketio.run(app, debug=os.getenv('FLASK_DEBUG', 'False').lower() == 'true')
|
|
||||||
|
Binary file not shown.
Before Width: | Height: | Size: 232 KiB |
Binary file not shown.
Before Width: | Height: | Size: 101 KiB |
@ -1,599 +1,371 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="es">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<title>Condor Business Solutions SecureScan</title>
|
||||||
<title>CBS CyberScan | Terminal Web de Escaneo</title>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js"></script>
|
||||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
<script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0"></script>
|
||||||
<style>
|
<style>
|
||||||
:root {
|
/* General styling */
|
||||||
--primary-color: #00ff8c;
|
body {
|
||||||
--secondary-color: #232b38;
|
background-color: #1e1e2f;
|
||||||
--accent-color: #0a4da3;
|
color: #dcdcdc;
|
||||||
--text-color: #ffffff;
|
font-family: 'Roboto', sans-serif;
|
||||||
--terminal-bg: #0a0a0a;
|
overflow: hidden; /* Para que no aparezca la barra de scroll */
|
||||||
--container-bg: rgba(35, 43, 56, 0.95);
|
|
||||||
}
|
}
|
||||||
|
h1 {
|
||||||
body {
|
color: #00d1b2;
|
||||||
background-color: #121212;
|
margin-bottom: 30px;
|
||||||
color: var(--text-color);
|
|
||||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
|
||||||
min-height: 100vh;
|
|
||||||
margin: 0;
|
|
||||||
padding: 20px 0;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
#particles-js {
|
|
||||||
position: fixed;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
z-index: -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.main-container {
|
|
||||||
flex: 1;
|
|
||||||
max-width: 1200px;
|
|
||||||
margin: 0 auto;
|
|
||||||
padding: 0 20px;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cyber-container {
|
|
||||||
background: var(--container-bg);
|
|
||||||
border: 1px solid var(--primary-color);
|
|
||||||
border-radius: 15px;
|
|
||||||
padding: 2rem;
|
|
||||||
box-shadow: 0 0 20px rgba(0, 255, 140, 0.2);
|
|
||||||
position: relative;
|
|
||||||
overflow: hidden;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cyber-title {
|
|
||||||
color: var(--primary-color);
|
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 2px;
|
|
||||||
text-align: center;
|
text-align: center;
|
||||||
margin: 1rem 0;
|
|
||||||
font-weight: 600;
|
|
||||||
font-size: 2rem;
|
|
||||||
text-shadow: 0 0 10px rgba(0, 255, 140, 0.5);
|
|
||||||
}
|
}
|
||||||
|
.container {
|
||||||
|
max-width: 600px;
|
||||||
|
margin: 40px auto;
|
||||||
|
padding: 20px;
|
||||||
|
background: rgba(41, 41, 61, 0.85); /* Fondo semi-transparente */
|
||||||
|
border-radius: 10px;
|
||||||
|
box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
|
||||||
|
position: relative; /* Necesario para el contenedor */
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
.form-control-file, .form-control, .btn {
|
||||||
|
border-radius: 50px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
}
|
||||||
|
.btn-primary, .btn-secondary {
|
||||||
|
width: 100%;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
}
|
||||||
|
.btn-primary:hover, .btn-secondary:hover {
|
||||||
|
background-color: #00b89c;
|
||||||
|
}
|
||||||
|
.btn-primary {
|
||||||
|
background-color: #00d1b2;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: #007bff;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
.progress {
|
||||||
|
height: 20px;
|
||||||
|
border-radius: 50px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.progress-bar {
|
||||||
|
transition: width 0.4s ease;
|
||||||
|
}
|
||||||
.terminal {
|
.terminal {
|
||||||
background-color: var(--terminal-bg);
|
height: 400px;
|
||||||
color: var(--primary-color);
|
overflow-y: scroll;
|
||||||
font-family: 'Courier New', Courier, monospace;
|
background-color: #1a1a2e;
|
||||||
|
color: #00d1b2;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
height: 400px;
|
box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.5);
|
||||||
overflow-y: auto;
|
font-family: 'Courier New', monospace;
|
||||||
border: 1px solid var(--primary-color);
|
|
||||||
box-shadow: 0 0 10px rgba(0, 255, 140, 0.2);
|
|
||||||
margin-top: 20px;
|
|
||||||
font-size: 14px;
|
|
||||||
line-height: 1.4;
|
|
||||||
word-wrap: break-word;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
position: relative;
|
|
||||||
}
|
}
|
||||||
|
/* Scrollbar styling */
|
||||||
.terminal::-webkit-scrollbar {
|
.terminal::-webkit-scrollbar {
|
||||||
width: 8px;
|
width: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.terminal::-webkit-scrollbar-track {
|
|
||||||
background: var(--terminal-bg);
|
|
||||||
}
|
|
||||||
|
|
||||||
.terminal::-webkit-scrollbar-thumb {
|
.terminal::-webkit-scrollbar-thumb {
|
||||||
background: var(--primary-color);
|
background-color: #00d1b2;
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.terminal-line {
|
|
||||||
display: inline;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
white-space: pre-wrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cursor {
|
|
||||||
display: inline-block;
|
|
||||||
width: 8px;
|
|
||||||
height: 16px;
|
|
||||||
background-color: var(--primary-color);
|
|
||||||
animation: blink 1s infinite;
|
|
||||||
margin-left: 2px;
|
|
||||||
vertical-align: middle;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes blink {
|
|
||||||
0%, 100% { opacity: 1; }
|
|
||||||
50% { opacity: 0; }
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-panel {
|
|
||||||
background: rgba(10, 77, 163, 0.1);
|
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
padding: 1.5rem;
|
|
||||||
margin-bottom: 1.5rem;
|
|
||||||
border: 1px solid var(--accent-color);
|
|
||||||
}
|
}
|
||||||
|
/* Responsive design */
|
||||||
.cyber-btn {
|
|
||||||
background: var(--secondary-color);
|
|
||||||
color: var(--primary-color);
|
|
||||||
border: 1px solid var(--primary-color);
|
|
||||||
padding: 10px 20px;
|
|
||||||
border-radius: 5px;
|
|
||||||
transition: all 0.3s ease;
|
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 1px;
|
|
||||||
font-weight: 600;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cyber-btn:hover:not(:disabled) {
|
|
||||||
background: var(--primary-color);
|
|
||||||
color: var(--secondary-color);
|
|
||||||
box-shadow: 0 0 15px var(--primary-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.cyber-btn:disabled {
|
|
||||||
opacity: 0.5;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cyber-input {
|
|
||||||
background: var(--terminal-bg);
|
|
||||||
border: 1px solid var(--primary-color);
|
|
||||||
color: var(--primary-color);
|
|
||||||
padding: 10px 15px;
|
|
||||||
border-radius: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cyber-input:focus {
|
|
||||||
outline: none;
|
|
||||||
box-shadow: 0 0 10px var(--primary-color);
|
|
||||||
border-color: var(--primary-color);
|
|
||||||
color: var(--primary-color);
|
|
||||||
background: var(--terminal-bg);
|
|
||||||
}
|
|
||||||
|
|
||||||
.progress {
|
|
||||||
height: 10px;
|
|
||||||
background: var(--terminal-bg);
|
|
||||||
border: 1px solid var(--primary-color);
|
|
||||||
border-radius: 5px;
|
|
||||||
margin: 15px 0;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.progress-bar {
|
|
||||||
background: linear-gradient(90deg, var(--primary-color), var(--accent-color));
|
|
||||||
transition: width 0.3s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.scan-stats {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
margin-top: 15px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stat-item {
|
|
||||||
background: rgba(10, 77, 163, 0.2);
|
|
||||||
padding: 10px;
|
|
||||||
border-radius: 5px;
|
|
||||||
border: 1px solid var(--accent-color);
|
|
||||||
flex: 1;
|
|
||||||
min-width: 200px;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.error-text {
|
|
||||||
color: #ff4444;
|
|
||||||
}
|
|
||||||
|
|
||||||
.success-text {
|
|
||||||
color: var(--primary-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.logo-container {
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.logo {
|
|
||||||
max-width: 50px;
|
|
||||||
height: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.cyber-container {
|
.container {
|
||||||
padding: 1rem;
|
width: 90%;
|
||||||
}
|
|
||||||
|
|
||||||
.terminal {
|
|
||||||
height: 300px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.control-panel {
|
|
||||||
padding: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.cyber-title {
|
|
||||||
font-size: 1.5rem;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/* Fullscreen background for particles */
|
||||||
|
#particles-js {
|
||||||
|
position: absolute;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
z-index: 0; /* Debajo del contenido principal */
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="particles-js"></div>
|
<div id="particles-js"></div>
|
||||||
|
<div class="container mt-4">
|
||||||
<div class="main-container">
|
<h1>Condor Business Solutions CyberScan|Terminal Web de Escaneo</h1>
|
||||||
<div class="cyber-container">
|
<input type="file" id="fileInput" class="form-control-file mb-3">
|
||||||
<div class="logo-container">
|
<button id="startScanBtn" class="btn btn-primary">Comenzar Escaneo</button>
|
||||||
<img src="https://condorbs.net/favicon.ico" alt="CBS Logo" class="logo">
|
<input type="text" id="urlInput" class="form-control" placeholder="Introduce una URL para escanear">
|
||||||
</div>
|
<button id="startUrlScanBtn" class="btn btn-secondary">Escanear URL</button>
|
||||||
|
<div id="progress" class="progress mt-3" style="display: none;">
|
||||||
<h1 class="cyber-title">
|
<div id="progressBar" class="progress-bar bg-success" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
|
||||||
<i class="fas fa-shield-alt"></i> CBS CyberScan
|
</div>
|
||||||
</h1>
|
<div id="scanOutput" class="terminal mt-4"></div>
|
||||||
|
<div id="signaturesUsed" class="mt-3" style="display: none;">
|
||||||
<div class="control-panel">
|
<strong>Número de firmas utilizadas:</strong> <span id="signaturesCount"></span>
|
||||||
<div class="row justify-content-center">
|
|
||||||
<div class="col-md-8">
|
|
||||||
<div class="d-grid gap-3">
|
|
||||||
<input type="file" id="fileInput" class="cyber-input" style="display: none;">
|
|
||||||
<button id="uploadBtn" onclick="document.getElementById('fileInput').click()" class="cyber-btn w-100">
|
|
||||||
<i class="fas fa-upload me-2"></i> Iniciar Escaneo
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div class="input-group">
|
|
||||||
<input type="url" id="urlInput" class="cyber-input form-control"
|
|
||||||
placeholder="Ingrese URL para escanear">
|
|
||||||
<button id="urlBtn" class="cyber-btn" onclick="scanUrl()">
|
|
||||||
<i class="fas fa-globe me-2"></i> Escanear URL
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="progress" class="progress" style="display: none;">
|
|
||||||
<div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;"
|
|
||||||
aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="scanOutput" class="terminal"></div>
|
|
||||||
|
|
||||||
<div class="scan-stats">
|
|
||||||
<div class="stat-item">
|
|
||||||
<i class="fas fa-clock"></i>
|
|
||||||
<span id="scanTime">Tiempo: 0s</span>
|
|
||||||
</div>
|
|
||||||
<div class="stat-item">
|
|
||||||
<i class="fas fa-shield-alt"></i>
|
|
||||||
<span id="scanStatus">Estado: Listo</span>
|
|
||||||
</div>
|
|
||||||
<div class="stat-item">
|
|
||||||
<i class="fas fa-virus-slash"></i>
|
|
||||||
<span id="threatCount">Amenazas: 0</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
|
<script type="text/javascript">
|
||||||
<script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
|
var socket = io.connect('http://' + document.domain + ':' + location.port);
|
||||||
<script>
|
|
||||||
// Terminal Writer Class
|
|
||||||
class TerminalWriter {
|
|
||||||
constructor(terminal) {
|
|
||||||
this.terminal = terminal;
|
|
||||||
this.queue = [];
|
|
||||||
this.isWriting = false;
|
|
||||||
this.typingSpeed = 5; // ms por carácter
|
|
||||||
this.lineDelay = 50; // ms entre líneas
|
|
||||||
}
|
|
||||||
|
|
||||||
write(text, type = '') {
|
document.getElementById('startScanBtn').onclick = function() {
|
||||||
return new Promise((resolve) => {
|
var fileInput = document.getElementById('fileInput');
|
||||||
this.queue.push({ text, type, resolve });
|
var file = fileInput.files[0];
|
||||||
if (!this.isWriting) {
|
|
||||||
this.processQueue();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async processQueue() {
|
if (!file) {
|
||||||
if (this.queue.length === 0) {
|
appendToTerminal('<span style="color: red;">Por favor selecciona un archivo.</span>');
|
||||||
this.isWriting = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.isWriting = true;
|
|
||||||
const { text, type, resolve } = this.queue.shift();
|
|
||||||
|
|
||||||
let formattedText = text;
|
|
||||||
if (type === 'error') {
|
|
||||||
formattedText = `<span class="error-text">${text}</span>`;
|
|
||||||
} else if (type === 'success') {
|
|
||||||
formattedText = `<span class="success-text">${text}</span>`;
|
|
||||||
} else if (text.toLowerCase().includes('found')) {
|
|
||||||
formattedText = `<span style="color: #ff4444;">${text}</span>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const newLine = document.createElement('span');
|
|
||||||
newLine.classList.add('terminal-line');
|
|
||||||
this.terminal.appendChild(newLine);
|
|
||||||
|
|
||||||
const cursor = document.createElement('span');
|
|
||||||
cursor.classList.add('cursor');
|
|
||||||
this.terminal.appendChild(cursor);
|
|
||||||
|
|
||||||
let charIndex = 0;
|
|
||||||
while (charIndex < formattedText.length) {
|
|
||||||
newLine.innerHTML = formattedText.substring(0, charIndex + 1);
|
|
||||||
charIndex++;
|
|
||||||
this.terminal.scrollTop = this.terminal.scrollHeight;
|
|
||||||
await this.sleep(this.typingSpeed);
|
|
||||||
}
|
|
||||||
|
|
||||||
cursor.remove();
|
|
||||||
await this.sleep(this.lineDelay);
|
|
||||||
resolve();
|
|
||||||
this.processQueue();
|
|
||||||
}
|
|
||||||
|
|
||||||
sleep(ms) {
|
|
||||||
return new Promise(resolve => setTimeout(resolve, ms));
|
|
||||||
}
|
|
||||||
|
|
||||||
clear() {
|
|
||||||
this.queue = [];
|
|
||||||
this.terminal.innerHTML = '';
|
|
||||||
this.isWriting = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize variables and socket connection
|
|
||||||
const socket = io();
|
|
||||||
let scanInProgress = false;
|
|
||||||
let scanStartTime;
|
|
||||||
let threatCount = 0;
|
|
||||||
let timerInterval;
|
|
||||||
|
|
||||||
const uploadBtn = document.getElementById('uploadBtn');
|
|
||||||
const urlBtn = document.getElementById('urlBtn');
|
|
||||||
const urlInput = document.getElementById('urlInput');
|
|
||||||
const scanTimeElement = document.getElementById('scanTime');
|
|
||||||
const scanStatusElement = document.getElementById('scanStatus');
|
|
||||||
const threatCountElement = document.getElementById('threatCount');
|
|
||||||
const terminalWriter = new TerminalWriter(document.getElementById('scanOutput'));
|
|
||||||
|
|
||||||
// Particles.js configuration
|
|
||||||
particlesJS('particles-js', {
|
|
||||||
particles: {
|
|
||||||
number: { value: 80 },
|
|
||||||
color: { value: '#00ff8c' },
|
|
||||||
shape: { type: 'circle' },
|
|
||||||
opacity: { value: 0.5, random: true },
|
|
||||||
size: { value: 3 },
|
|
||||||
line_linked: {
|
|
||||||
enable: true,
|
|
||||||
color: '#00ff8c',
|
|
||||||
opacity: 0.4
|
|
||||||
},
|
|
||||||
move: {
|
|
||||||
enable: true,
|
|
||||||
speed: 3,
|
|
||||||
direction: 'none',
|
|
||||||
random: true,
|
|
||||||
straight: false,
|
|
||||||
out_mode: 'out'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
interactivity: {
|
|
||||||
detect_on: 'canvas',
|
|
||||||
events: {
|
|
||||||
onhover: {
|
|
||||||
enable: true,
|
|
||||||
mode: 'repulse'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
function toggleControls(disabled) {
|
|
||||||
uploadBtn.disabled = disabled;
|
|
||||||
urlBtn.disabled = disabled;
|
|
||||||
urlInput.disabled = disabled;
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateProgress(progress) {
|
|
||||||
const progressBar = document.getElementById('progressBar');
|
|
||||||
progressBar.style.width = `${progress}%`;
|
|
||||||
progressBar.setAttribute('aria-valuenow', progress);
|
|
||||||
}
|
|
||||||
|
|
||||||
function startScanTimer() {
|
|
||||||
scanStartTime = Date.now();
|
|
||||||
clearInterval(timerInterval);
|
|
||||||
timerInterval = setInterval(updateTimer, 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateTimer() {
|
|
||||||
const elapsedTime = Math.floor((Date.now() - scanStartTime) / 1000);
|
|
||||||
scanTimeElement.textContent = `Tiempo: ${elapsedTime}s`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resetStats() {
|
|
||||||
threatCount = 0;
|
|
||||||
scanTimeElement.textContent = 'Tiempo: 0s';
|
|
||||||
scanStatusElement.textContent = 'Estado: Escaneando';
|
|
||||||
scanStatusElement.style.color = '#00ff8c';
|
|
||||||
threatCountElement.textContent = 'Amenazas: 0';
|
|
||||||
clearInterval(timerInterval);
|
|
||||||
}
|
|
||||||
|
|
||||||
function scanUrl() {
|
|
||||||
const url = urlInput.value;
|
|
||||||
if (!url) {
|
|
||||||
appendToTerminal('Error: Por favor ingrese una URL\n', 'error');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
startScan();
|
appendToTerminal('<span style="color: green;">Subiendo archivo: ' + file.name + '</span>');
|
||||||
fetch('/scan_url', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ url: url })
|
|
||||||
})
|
|
||||||
.then(handleResponse)
|
|
||||||
.catch(handleError);
|
|
||||||
}
|
|
||||||
|
|
||||||
document.getElementById('fileInput').addEventListener('change', function(e) {
|
var formData = new FormData();
|
||||||
if (e.target.files.length === 0) return;
|
|
||||||
|
|
||||||
const file = e.target.files[0];
|
|
||||||
const formData = new FormData();
|
|
||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
|
|
||||||
startScan();
|
// Mostrar la barra de progreso y ocultar el botón
|
||||||
|
document.getElementById('progress').style.display = 'block';
|
||||||
|
document.getElementById('startScanBtn').style.display = 'none';
|
||||||
|
|
||||||
fetch('/upload', {
|
fetch('/upload', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: formData
|
body: formData
|
||||||
})
|
})
|
||||||
.then(handleResponse)
|
.then(response => response.text())
|
||||||
.catch(handleError);
|
.then(data => {
|
||||||
});
|
appendToTerminal('<span style="color: green;">' + data + '</span>');
|
||||||
|
// Restablecer la visibilidad del botón después del escaneo
|
||||||
|
document.getElementById('startScanBtn').style.display = 'block';
|
||||||
|
document.getElementById('progress').style.display = 'none';
|
||||||
|
document.getElementById('progressBar').style.width = '0%';
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
appendToTerminal('<span style="color: red;">Error al subir el archivo: ' + error + '</span>');
|
||||||
|
// Restablecer la visibilidad del botón en caso de error
|
||||||
|
document.getElementById('startScanBtn').style.display = 'block';
|
||||||
|
document.getElementById('progress').style.display = 'none';
|
||||||
|
document.getElementById('progressBar').style.width = '0%';
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
function startScan() {
|
document.getElementById('startScanBtn').onclick = function() {
|
||||||
terminalWriter.clear();
|
var fileInput = document.getElementById('fileInput');
|
||||||
|
var file = fileInput.files[0];
|
||||||
|
|
||||||
|
if (!file) {
|
||||||
|
appendToTerminal('<span style="color: red;">Por favor selecciona un archivo.</span>');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
appendToTerminal('<span style="color: green;">Subiendo archivo: ' + file.name + '</span>');
|
||||||
|
|
||||||
|
var formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
|
||||||
|
// Mostrar la barra de progreso y ocultar el botón
|
||||||
document.getElementById('progress').style.display = 'block';
|
document.getElementById('progress').style.display = 'block';
|
||||||
scanInProgress = true;
|
document.getElementById('startScanBtn').style.display = 'none';
|
||||||
toggleControls(true);
|
|
||||||
resetStats();
|
|
||||||
startScanTimer();
|
|
||||||
updateProgress(20);
|
|
||||||
threatCount = 0;
|
|
||||||
threatCountElement.textContent = 'Amenazas: 0';
|
|
||||||
scanStatusElement.textContent = 'Estado: Escaneando';
|
|
||||||
scanStatusElement.style.color = '#00ff8c';
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleResponse(response) {
|
fetch('/upload', {
|
||||||
return response.json().then(data => {
|
method: 'POST',
|
||||||
if (data.error) {
|
body: formData
|
||||||
appendToTerminal('Error: ' + data.error + '\n', 'error');
|
})
|
||||||
finishScan(false);
|
.then(response => response.text())
|
||||||
} else {
|
.then(data => {
|
||||||
if (data.result) {
|
appendToTerminal('<span style="color: green;">' + data + '</span>');
|
||||||
appendToTerminal('Yo a este lo conozco\n', 'success');
|
// Restablecer la visibilidad del botón después del escaneo
|
||||||
appendToTerminal('Fecha de escaneo previo: ' + data.result.scan_date + '\n');
|
document.getElementById('startScanBtn').style.display = 'block';
|
||||||
appendToTerminal('Tipo de archivo: ' + data.result.file_type + '\n');
|
document.getElementById('progress').style.display = 'none';
|
||||||
appendToTerminal('\nResultado del escaneo previo:\n');
|
document.getElementById('progressBar').style.width = '0%';
|
||||||
appendToTerminal(data.result.scan_result + '\n');
|
// Limpiar el input de archivo
|
||||||
|
document.getElementById('fileInput').value = '';
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
appendToTerminal('<span style="color: red;">Error al subir el archivo: ' + error + '</span>');
|
||||||
|
// Restablecer la visibilidad del botón en caso de error
|
||||||
|
document.getElementById('startScanBtn').style.display = 'block';
|
||||||
|
document.getElementById('progress').style.display = 'none';
|
||||||
|
document.getElementById('progressBar').style.width = '0%';
|
||||||
|
// Limpiar el input de archivo en caso de error
|
||||||
|
document.getElementById('fileInput').value = '';
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
if (data.result.scan_result.toLowerCase().includes('found')) {
|
document.getElementById('startUrlScanBtn').onclick = function() {
|
||||||
threatCount++;
|
var urlInput = document.getElementById('urlInput').value;
|
||||||
threatCountElement.textContent = `Amenazas: ${threatCount}`;
|
|
||||||
scanStatusElement.textContent = 'Estado: Amenaza Detectada';
|
|
||||||
scanStatusElement.style.color = '#ff4444';
|
|
||||||
}
|
|
||||||
|
|
||||||
finishScan(true);
|
if (!urlInput) {
|
||||||
|
appendToTerminal('<span style="color: red;">Por favor introduce una URL.</span>');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asegurar que la URL tenga un esquema
|
||||||
|
if (!urlInput.startsWith('http://') && !urlInput.startsWith('https://')) {
|
||||||
|
urlInput = 'http://' + urlInput;
|
||||||
|
}
|
||||||
|
|
||||||
|
appendToTerminal('<span style="color: green;">Escaneando URL: ' + urlInput + '</span>');
|
||||||
|
|
||||||
|
// Mostrar la barra de progreso y ocultar el botón
|
||||||
|
document.getElementById('progress').style.display = 'block';
|
||||||
|
document.getElementById('startUrlScanBtn').style.display = 'none';
|
||||||
|
|
||||||
|
fetch('/scan_url', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ url: urlInput })
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
// Comprobar si la respuesta es JSON
|
||||||
|
const contentType = response.headers.get('content-type');
|
||||||
|
if (contentType && contentType.includes('application/json')) {
|
||||||
|
return response.json();
|
||||||
} else {
|
} else {
|
||||||
appendToTerminal('Iniciando nuevo escaneo...\n');
|
return response.text(); // Si no es JSON, tratarlo como texto
|
||||||
updateProgress(40);
|
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
});
|
.then(data => {
|
||||||
}
|
if (typeof data === 'string') {
|
||||||
|
appendToTerminal('<span style="color: red;">Respuesta inesperada: ' + data + '</span>');
|
||||||
|
} else if (data.error) {
|
||||||
|
appendToTerminal('<span style="color: red;">Error: ' + data.error + '</span>');
|
||||||
|
} else {
|
||||||
|
appendToTerminal('<span style="color: green;">' + data.message + '</span>');
|
||||||
|
}
|
||||||
|
// Restablecer la visibilidad del botón después del escaneo
|
||||||
|
document.getElementById('startUrlScanBtn').style.display = 'block';
|
||||||
|
document.getElementById('progress').style.display = 'none';
|
||||||
|
document.getElementById('progressBar').style.width = '0%';
|
||||||
|
// Limpiar el input de URL
|
||||||
|
document.getElementById('urlInput').value = '';
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
appendToTerminal('<span style="color: red;">Error al escanear la URL: ' + error + '</span>');
|
||||||
|
// Restablecer la visibilidad del botón en caso de error
|
||||||
|
document.getElementById('startUrlScanBtn').style.display = 'block';
|
||||||
|
document.getElementById('progress').style.display = 'none';
|
||||||
|
document.getElementById('progressBar').style.width = '0%';
|
||||||
|
// Limpiar el input de URL en caso de error
|
||||||
|
document.getElementById('urlInput').value = '';
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
function handleError(error) {
|
|
||||||
appendToTerminal('Error: ' + error + '\n', 'error');
|
|
||||||
finishScan(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
socket.on('scan_output', function(data) {
|
socket.on('scan_output', function(data) {
|
||||||
appendToTerminal(data.data);
|
appendToTerminal(data.data);
|
||||||
updateProgress(60);
|
|
||||||
|
|
||||||
if (data.data.toLowerCase().includes('found')) {
|
// Parsear porcentaje de progreso si está presente
|
||||||
threatCount++;
|
var progressMatch = data.data.match(/(\d+\.\d+)%/);
|
||||||
threatCountElement.textContent = `Amenazas: ${threatCount}`;
|
if (progressMatch) {
|
||||||
scanStatusElement.textContent = 'Estado: Amenaza Detectada';
|
var percent = parseFloat(progressMatch[1]);
|
||||||
scanStatusElement.style.color = '#ff4444';
|
updateProgressBar(percent);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.data.includes('Infected files:')) {
|
// Mostrar el número de firmas utilizadas (filtrando solo el número)
|
||||||
const match = data.data.match(/Infected files:\s*(\d+)/);
|
var signaturesMatch = data.data.match(/Known viruses: (\d+)/);
|
||||||
if (match) {
|
if (signaturesMatch) {
|
||||||
const infectedCount = parseInt(match[1]);
|
document.getElementById('signaturesUsed').style.display = 'block';
|
||||||
if (infectedCount > 0) {
|
document.getElementById('signaturesCount').textContent = signaturesMatch[1];
|
||||||
threatCount = infectedCount;
|
|
||||||
threatCountElement.textContent = `Amenazas: ${threatCount}`;
|
|
||||||
scanStatusElement.textContent = 'Estado: Amenazas Detectadas';
|
|
||||||
scanStatusElement.style.color = '#ff4444';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
updateProgress(80);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.data.includes('--- Escaneo completado ---')) {
|
|
||||||
finishScan(true);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
function appendToTerminal(text, type = '') {
|
function appendToTerminal(message) {
|
||||||
terminalWriter.write(text, type);
|
var scanOutput = document.getElementById('scanOutput');
|
||||||
|
var newLine = document.createElement('div');
|
||||||
|
newLine.innerHTML = message;
|
||||||
|
scanOutput.appendChild(newLine);
|
||||||
|
scanOutput.scrollTop = scanOutput.scrollHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
function finishScan(success = true) {
|
function updateProgressBar(percent) {
|
||||||
scanInProgress = false;
|
var progressBar = document.getElementById('progressBar');
|
||||||
toggleControls(false);
|
progressBar.style.width = percent + '%';
|
||||||
document.getElementById('progress').style.display = 'none';
|
progressBar.setAttribute('aria-valuenow', percent);
|
||||||
updateProgress(100);
|
progressBar.innerHTML = percent.toFixed(2) + '%';
|
||||||
clearInterval(timerInterval);
|
}
|
||||||
|
|
||||||
if (success) {
|
// Configurar particles.js
|
||||||
if (threatCount > 0) {
|
particlesJS('particles-js', {
|
||||||
scanStatusElement.textContent = `Estado: ${threatCount} Amenaza(s) Detectada(s)`;
|
"particles": {
|
||||||
scanStatusElement.style.color = '#ff4444';
|
"number": {
|
||||||
} else {
|
"value": 80,
|
||||||
scanStatusElement.textContent = 'Estado: Archivo Seguro';
|
"density": {
|
||||||
scanStatusElement.style.color = '#00ff8c';
|
"enable": true,
|
||||||
|
"value_area": 800
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"color": {
|
||||||
|
"value": "#ffffff"
|
||||||
|
},
|
||||||
|
"shape": {
|
||||||
|
"type": "circle",
|
||||||
|
"stroke": {
|
||||||
|
"width": 0,
|
||||||
|
"color": "#000000"
|
||||||
|
},
|
||||||
|
"polygon": {
|
||||||
|
"nb_sides": 5
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"opacity": {
|
||||||
|
"value": 0.5,
|
||||||
|
"random": false,
|
||||||
|
"anim": {
|
||||||
|
"enable": false,
|
||||||
|
"speed": 1,
|
||||||
|
"opacity_min": 0.1,
|
||||||
|
"sync": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"size": {
|
||||||
|
"value": 3,
|
||||||
|
"random": true,
|
||||||
|
"anim": {
|
||||||
|
"enable": false,
|
||||||
|
"speed": 40,
|
||||||
|
"size_min": 0.1,
|
||||||
|
"sync": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"line_linked": {
|
||||||
|
"enable": true,
|
||||||
|
"distance": 150,
|
||||||
|
"color": "#ffffff",
|
||||||
|
"opacity": 0.4,
|
||||||
|
"width": 1
|
||||||
|
},
|
||||||
|
"move": {
|
||||||
|
"enable": true,
|
||||||
|
"speed": 6,
|
||||||
|
"direction": "none",
|
||||||
|
"random": false,
|
||||||
|
"straight": false,
|
||||||
|
"out_mode": "out",
|
||||||
|
"attract": {
|
||||||
|
"enable": false,
|
||||||
|
"rotateX": 600,
|
||||||
|
"rotateY": 1200
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
},
|
||||||
scanStatusElement.textContent = 'Estado: Error';
|
"interactivity": {
|
||||||
scanStatusElement.style.color = '#ff4444';
|
"detect_on": "canvas",
|
||||||
}
|
"events": {
|
||||||
|
"onhover": {
|
||||||
document.getElementById('fileInput').value = '';
|
"enable": false
|
||||||
urlInput.value = '';
|
},
|
||||||
}
|
"onclick": {
|
||||||
|
"enable": false
|
||||||
// Inicialización al cargar la página
|
},
|
||||||
window.onload = function() {
|
"resize": true
|
||||||
document.getElementById('fileInput').value = '';
|
},
|
||||||
document.getElementById('urlInput').value = '';
|
},
|
||||||
updateProgress(0);
|
"retina_detect": true
|
||||||
toggleControls(false);
|
});
|
||||||
document.getElementById('progress').style.display = 'none';
|
|
||||||
};
|
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
Loading…
x
Reference in New Issue
Block a user