From 5487b994c106147aee4b7f4156788cf9d493cd32 Mon Sep 17 00:00:00 2001 From: luisgulo Date: Sun, 8 Nov 2026 03:25:59 +0100 Subject: [PATCH] Ajuste peticiones API y paginacion --- build.sh | 2 + index.html | 508 ++++++++++++++++++++++++++++++++++++++++++++++++ proxy-harbor.py | 277 +++++++++++++++++++++----- run_docker.sh | 5 + stop_docker.sh | 2 + 5 files changed, 741 insertions(+), 53 deletions(-) create mode 100755 build.sh create mode 100644 index.html create mode 100755 run_docker.sh create mode 100755 stop_docker.sh diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..39557ec --- /dev/null +++ b/build.sh @@ -0,0 +1,2 @@ +#!/bin/bash +docker build --no-cache -t harbor-security-portal . diff --git a/index.html b/index.html new file mode 100644 index 0000000..989c4bb --- /dev/null +++ b/index.html @@ -0,0 +1,508 @@ + + + + + + Portal de Seguridad Harbor - Inspector de Vulnerabilidades y SBOM + + + + + + +
+
+
+ +
+
+

+ Portal de Seguridad Harbor + API v2.0 Live +

+

Inspector Centralizado de Vulnerabilidades vía API

+
+
+ +
+
+ + Sin Autenticar +
+ + + + + +
+
+ +
+ +
+
+

Total CVEs

0

+
+
+
+

Críticas

0

+
+
+
+

Altas

0

+
+
+
+

Medias

0

+
+
+
+

Bajas

0

+
+
+
+ + +
+

+ Búsqueda Directa en API de Harbor (/security/vul) +

+ +
+
+ + +
+ +
+ +
+ +
+ +
+
+
+ + +
+
+ Registros en página actual: 0 + +
+ Mostrar: + + por página +
+
+ +
+ + + + + + + + + + + + + + +
CVE IDSeveridadPaquete AfectadoProyectoRepositorioTag / DigestCVSS3Acciones
+
+
+
+

Realiza una búsqueda para consultar la API

+

Selecciona un filtro superior y pulsa SEARCH API.

+
+ + +
+ + Página 1 + +
+ + +
+
+
+
+ + + + + + + + + + \ No newline at end of file diff --git a/proxy-harbor.py b/proxy-harbor.py index 1841508..446afab 100644 --- a/proxy-harbor.py +++ b/proxy-harbor.py @@ -1,65 +1,236 @@ +import os import http.server import urllib.request -import base64 +import urllib.error import json +from urllib.parse import urlparse, parse_qs, urlencode +HARBOR_URL = os.environ.get("HARBOR_URL", "https://demo.goharbor.io").rstrip("/") PORT = 8080 -# Cambia esto por tu URL de Harbor real -HARBOR_URL = "https://harbor.midominio.com" -class ProxyHandler(http.server.SimpleHTTPRequestHandler): - def do_GET(self): - # Si la petición va dirigida a la API, la redirigimos a Harbor haciendo de proxy - if self.path.startswith("/api/"): - target_url = HARBOR_URL + self.path - - # Recuperamos las cabeceras de autorización que envíe el navegador - auth_header = self.headers.get('Authorization') - - req = urllib.request.Request(target_url) - if auth_header: - req.add_header('Authorization', auth_header) - - try: - # Realizamos la petición a Harbor ignorando problemas de certificados internos si los hubiera - import ssl - ctx = ssl.create_default_context() - ctx.check_hostname = False - ctx.verify_mode = ssl.CERT_NONE - - with urllib.request.urlopen(req, context=ctx) as response: - data = response.read() - self.send_response(response.status) - self.send_header('Content-Type', response.headers.get('Content-Type', 'application/json')) - # Añadimos las cabeceras CORS para que el navegador no se queje nunca más - self.send_header('Access-Control-Allow-Origin', '*') - self.end_headers() - self.wfile.write(data) - except urllib.error.HTTPError as e: - self.send_response(e.code) - self.end_headers() - self.wfile.write(e.read()) - except Exception as e: - self.send_response(500) - self.end_headers() - self.wfile.write(str(e).encode('utf-8')) - else: - # Para cualquier otra ruta, sirve los archivos estáticos normales (tu HTML) - super().do_GET() +def fetch_json(url, auth_header): + req = urllib.request.Request(url) + req.add_header("Accept", "application/json") + if auth_header: + req.add_header("Authorization", auth_header) + try: + with urllib.request.urlopen(req, timeout=8) as response: + return json.loads(response.read().decode("utf-8")) + except Exception: + return None +class HarborProxyHandler(http.server.BaseHTTPRequestHandler): + def do_OPTIONS(self): - # Respondemos automáticamente al preflight de CORS del navegador self.send_response(200) - self.send_header('Access-Control-Allow-Origin', '*') - self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') - self.send_header('Access-Control-Allow-Headers', 'Authorization, Content-Type') + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type") self.end_headers() + def do_GET(self): + parsed_url = urlparse(self.path) + path = parsed_url.path + query_params = {k: v[0] for k, v in parse_qs(parsed_url.query).items()} + auth_header = self.headers.get("Authorization") + + if path == "/" or path == "/index.html": + self.serve_file("index.html", "text/html") + return + elif path.startswith("/assets/"): + self.serve_static_asset() + return + + # ENDPOINT DE MÉTRICAS GLOBALES (SUMMARY) + if path == "/api/summary": + target_api = f"{HARBOR_URL}/api/v2.0/security/summary?with_dangerous_cve=false&with_dangerous_artifact=false" + req = urllib.request.Request(target_api) + req.add_header("Accept", "application/json") + if auth_header: + req.add_header("Authorization", auth_header) + try: + with urllib.request.urlopen(req, timeout=10) as response: + data = response.read() + self.send_response(response.status) + self.send_header("Content-Type", "application/json") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(data) + except Exception as e: + self.send_json_response({}) + return + + # ENDPOINT DE EXPORTACIÓN MASIVA (CSV/EXCEL) + if path == "/api/export": + self.handle_export_vulnerabilities(query_params, auth_header) + return + + # BÚSQUEDA NATIVA /security/vul CON PAGINACIÓN + if path == "/api/search": + self.handle_native_vulnerability_search(query_params, auth_header) + return + + target_url = f"{HARBOR_URL}{path}" + if parsed_url.query: + target_url += f"?{parsed_url.query}" + + req = urllib.request.Request(target_url) + req.add_header("Accept", "application/json") + if auth_header: + req.add_header("Authorization", auth_header) + + try: + with urllib.request.urlopen(req) as response: + data = response.read() + self.send_response(response.status) + self.send_header("Content-Type", "application/json") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(data) + except urllib.error.HTTPError as e: + self.send_response(e.code) + self.send_header("Content-Type", "application/json") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(e.read()) + except Exception as e: + self.send_response(500) + self.send_header("Content-Type", "application/json") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(json.dumps({"error": str(e)}).encode("utf-8")) + + def handle_native_vulnerability_search(self, params, auth_header): + self._process_vul_search(params, auth_header, is_export=False) + + def handle_export_vulnerabilities(self, params, auth_header): + self._process_vul_search(params, auth_header, is_export=True) + + def _process_vul_search(self, params, auth_header, is_export=False): + filter_type = params.get("filter_type", "All") + query = params.get("query", "").strip() + severity_raw = params.get("severity", "").strip() + cvss_from = params.get("cvss_from", "").strip() + cvss_to = params.get("cvss_to", "").strip() + + page = "1" if is_export else params.get("page", "1") + page_size = "500" if is_export else params.get("page_size", "10") + + q_conditions = [] + project_map = {} + + try: + # Mapeo rápido de proyectos opcional solo para mostrar nombres bonitos en la tabla si hiciera falta + projects_data = fetch_json(f"{HARBOR_URL}/api/v2.0/projects?page_size=100", auth_header) + if projects_data: + for p in projects_data: + project_map[p.get("project_id")] = p.get("name") + + if filter_type == "CVE ID" and query: + q_conditions.append(f"cve_id={query}") + elif filter_type == "Package" and query: + q_conditions.append(f"package={query}") + elif filter_type == "Repository Name" and query: + # Búsqueda directa por repositorio (ej: demo8/mysql) + q_conditions.append(f"repository_name={query}") + elif filter_type == "Digest" and query: + q_conditions.append(f"digest={query}") + elif filter_type == "Severity" and severity_raw and severity_raw.upper() != "ALL": + sev_map = { + "CRITICAL": "Critical", + "HIGH": "High", + "MEDIUM": "Medium", + "LOW": "Low", + "N/A": "n/a", + "NONE": "None" + } + mapped_sev = sev_map.get(severity_raw.upper(), severity_raw.capitalize()) + q_conditions.append(f"severity={mapped_sev}") + elif filter_type == "CVSS3": + min_val = cvss_from if cvss_from else "0" + max_val = cvss_to if cvss_to else "10" + q_conditions.append(f"cvss_score_v3=[{min_val}~{max_val}]") + + api_params = { + "page": page, + "page_size": page_size, + "tune_count": "false", + "with_tag": "true" + } + + if q_conditions: + api_params["q"] = ",".join(q_conditions) + + target_api = f"{HARBOR_URL}/api/v2.0/security/vul?{urlencode(api_params)}" + print(f"[*] Consultando API nativa de Harbor: {target_api}") + + req = urllib.request.Request(target_api) + req.add_header("Accept", "application/json") + if auth_header: + req.add_header("Authorization", auth_header) + + with urllib.request.urlopen(req, timeout=15) as response: + raw_data = json.loads(response.read().decode("utf-8")) + + formatted_results = [] + for item in raw_data: + p_id = item.get("project_id") + project_name = project_map.get(p_id, str(p_id)) + repo_name = item.get("repository_name", "") + + formatted_results.append({ + "cve_id": item.get("cve_id", "N/A"), + "severity": item.get("severity", "UNKNOWN").upper(), + "package": item.get("package", "Desconocido"), + "version": item.get("version", "-"), + "fixed_version": item.get("fixed_version", "N/A"), + "project": project_name, + "repository": repo_name, + "tag": item.get("tags", ["latest"])[0] if item.get("tags") else "latest", + "digest": item.get("digest", "N/A"), + "cvss3": float(item.get("cvss_v3_score", 0)), + "description": item.get("desc", "Sin descripción.") + }) + + self.send_json_response(formatted_results) + except urllib.error.HTTPError as e: + print(f"[!] Error HTTP de Harbor en /security/vul: {e.code}") + self.send_json_response([]) + except Exception as e: + print(f"[!] Error en consulta nativa: {e}") + self.send_json_response([]) + + def send_json_response(self, data): + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(json.dumps(data).encode("utf-8")) + + def serve_file(self, filename, content_type): + if os.path.exists(filename): + with open(filename, "rb") as f: + content = f.read() + self.send_response(200) + self.send_header("Content-Type", content_type) + self.end_headers() + self.wfile.write(content) + else: + self.send_response(404) + self.end_headers() + + def serve_static_asset(self): + filepath = self.path.lstrip("/") + if os.path.exists(filepath): + content_type = "text/plain" + if filepath.endswith(".js"): content_type = "application/javascript" + elif filepath.endswith(".css"): content_type = "text/css" + self.serve_file(filepath, content_type) + else: + self.send_response(404) + self.end_headers() + if __name__ == "__main__": - server_address = ('', PORT) - httpd = http.server.HTTPServer(server_address, ProxyHandler) - print(f"---------------------------------------------------------") - print(f"Servidor proxy y web corriendo en http://localhost:{PORT}") - print(f"---------------------------------------------------------") - print(f"\nUse la URL http://localhost:{PORT} para Harbor\nen vez de {HARBOR_URL}") - httpd.serve_forever() + server = http.server.HTTPServer(("0.0.0.0", PORT), HarborProxyHandler) + print(f"[*] Proxy Harbor con repositorio directo corriendo en el puerto {PORT}, conectado a: {HARBOR_URL}") + server.serve_forever() \ No newline at end of file diff --git a/run_docker.sh b/run_docker.sh new file mode 100755 index 0000000..bc7923e --- /dev/null +++ b/run_docker.sh @@ -0,0 +1,5 @@ +#!/bin/bash +docker rm -f portal-harbor 2> /dev/null +#docker run -d -p 8080:8080 -e HARBOR_URL="https://tu-harbor-corporativo.com" --name portal-harbor harbor-security-portal +docker run -d -p 8080:8080 -e HARBOR_URL="https://demo.goharbor.io" --name portal-harbor harbor-security-portal +echo "Portal Harbor iniciado en http://localhost:8080" diff --git a/stop_docker.sh b/stop_docker.sh new file mode 100755 index 0000000..067d5e8 --- /dev/null +++ b/stop_docker.sh @@ -0,0 +1,2 @@ +#!/bin/bash +docker rm -f portal-harbor