-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
288 lines (262 loc) · 10.6 KB
/
app.py
File metadata and controls
288 lines (262 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import os
import sqlite3
from datetime import datetime
from ipaddress import ip_address, ip_network
from typing import Any, Dict
from flask import Flask, flash, jsonify, redirect, render_template, request, url_for
DATABASE = "xero_net.db"
def create_app() -> Flask:
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET", "change-me")
def get_db_connection() -> sqlite3.Connection:
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
def init_db() -> None:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS prefixes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
family TEXT NOT NULL,
cidr TEXT NOT NULL UNIQUE,
assigned_to TEXT,
notes TEXT,
created_at TEXT NOT NULL
)
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS firewall_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
action TEXT NOT NULL,
target TEXT NOT NULL,
scope TEXT NOT NULL,
reason TEXT,
created_at TEXT NOT NULL
)
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS nodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
api_url TEXT NOT NULL,
api_token TEXT NOT NULL,
created_at TEXT NOT NULL
)
"""
)
conn.commit()
conn.close()
def parse_prefix(cidr: str) -> Dict[str, str]:
network = ip_network(cidr, strict=False)
return {"family": f"IPv{network.version}", "cidr": str(network)}
def validate_target(target: str) -> str:
try:
network = ip_network(target, strict=False)
return str(network)
except ValueError:
try:
return str(ip_address(target))
except ValueError as exc: # pragma: no cover - guard clause
raise ValueError("El destino debe ser una IP o prefijo válido") from exc
@app.before_request
def ensure_db() -> None:
init_db()
@app.route("/")
def dashboard():
conn = get_db_connection()
prefixes = conn.execute("SELECT * FROM prefixes ORDER BY created_at DESC").fetchall()
firewall_rules = conn.execute(
"SELECT * FROM firewall_rules ORDER BY created_at DESC"
).fetchall()
nodes = conn.execute("SELECT * FROM nodes ORDER BY created_at DESC").fetchall()
conn.close()
assigned = [p for p in prefixes if p["assigned_to"]]
unassigned = [p for p in prefixes if not p["assigned_to"]]
family_counts = {"IPv4": 0, "IPv6": 0}
for prefix in prefixes:
family_counts[prefix["family"]] = family_counts.get(prefix["family"], 0) + 1
return render_template(
"dashboard.html",
prefixes=prefixes,
firewall_rules=firewall_rules,
nodes=nodes,
assigned_count=len(assigned),
unassigned_count=len(unassigned),
family_counts=family_counts,
)
@app.route("/prefixes", methods=["GET", "POST"])
def manage_prefixes():
conn = get_db_connection()
if request.method == "POST":
cidr = request.form.get("cidr", "").strip()
notes = request.form.get("notes", "").strip()
try:
parsed = parse_prefix(cidr)
except ValueError as exc:
flash(str(exc), "danger")
else:
try:
conn.execute(
"INSERT INTO prefixes (family, cidr, notes, created_at) VALUES (?, ?, ?, ?)",
(parsed["family"], parsed["cidr"], notes, datetime.utcnow().isoformat()),
)
conn.commit()
flash("Prefijo agregado.", "success")
except sqlite3.IntegrityError:
flash("El prefijo ya existe.", "warning")
prefixes = conn.execute("SELECT * FROM prefixes ORDER BY created_at DESC").fetchall()
conn.close()
return render_template("prefixes.html", prefixes=prefixes)
@app.post("/prefixes/<int:prefix_id>/assign")
def assign_prefix(prefix_id: int):
assigned_to = request.form.get("assigned_to", "").strip()
notes = request.form.get("notes", "").strip()
conn = get_db_connection()
conn.execute(
"UPDATE prefixes SET assigned_to = ?, notes = ? WHERE id = ?",
(assigned_to or None, notes, prefix_id),
)
conn.commit()
conn.close()
flash("Prefijo asignado/actualizado.", "success")
return redirect(url_for("manage_prefixes"))
@app.post("/prefixes/<int:prefix_id>/release")
def release_prefix(prefix_id: int):
conn = get_db_connection()
conn.execute(
"UPDATE prefixes SET assigned_to = NULL WHERE id = ?",
(prefix_id,),
)
conn.commit()
conn.close()
flash("Prefijo liberado.", "info")
return redirect(url_for("manage_prefixes"))
@app.route("/firewall", methods=["GET", "POST"])
def firewall():
conn = get_db_connection()
if request.method == "POST":
target = request.form.get("target", "").strip()
scope = request.form.get("scope", "global").strip() or "global"
reason = request.form.get("reason", "").strip()
action = request.form.get("action", "block").strip()
try:
normalized_target = validate_target(target)
except ValueError as exc:
flash(str(exc), "danger")
else:
conn.execute(
"INSERT INTO firewall_rules (action, target, scope, reason, created_at) VALUES (?, ?, ?, ?, ?)",
(
action,
normalized_target,
scope,
reason,
datetime.utcnow().isoformat(),
),
)
conn.commit()
flash("Regla de firewall creada.", "success")
rules = conn.execute("SELECT * FROM firewall_rules ORDER BY created_at DESC").fetchall()
conn.close()
return render_template("firewall.html", rules=rules)
@app.route("/nodes", methods=["GET", "POST"])
def manage_nodes():
conn = get_db_connection()
if request.method == "POST":
name = request.form.get("name", "").strip()
api_url = request.form.get("api_url", "").strip()
api_token = request.form.get("api_token", "").strip()
if name and api_url and api_token:
conn.execute(
"INSERT INTO nodes (name, api_url, api_token, created_at) VALUES (?, ?, ?, ?)",
(name, api_url, api_token, datetime.utcnow().isoformat()),
)
conn.commit()
flash("Nodo agregado.", "success")
else:
flash("Todos los campos de nodo son obligatorios.", "danger")
nodes = conn.execute("SELECT * FROM nodes ORDER BY created_at DESC").fetchall()
conn.close()
return render_template("nodes.html", nodes=nodes)
@app.post("/firewall/<int:rule_id>/push")
def push_rule(rule_id: int):
conn = get_db_connection()
rule = conn.execute(
"SELECT * FROM firewall_rules WHERE id = ?", (rule_id,)
).fetchone()
nodes = conn.execute("SELECT * FROM nodes").fetchall()
conn.close()
if not rule:
flash("Regla no encontrada.", "danger")
elif not nodes:
flash("No hay nodos configurados para sincronizar.", "warning")
else:
# Aqui podría ir la llamada real a APIs de los nodos.
flash(
f"Regla {rule['action']} {rule['target']} enviada a {len(nodes)} nodos.",
"info",
)
return redirect(url_for("firewall"))
# API endpoints
@app.get("/api/prefixes")
def api_prefixes():
conn = get_db_connection()
prefixes = conn.execute("SELECT * FROM prefixes").fetchall()
conn.close()
return jsonify([dict(row) for row in prefixes])
@app.post("/api/prefixes")
def api_create_prefix():
payload: Dict[str, Any] = request.get_json(force=True)
cidr = str(payload.get("cidr", "")).strip()
notes = str(payload.get("notes", "")).strip()
parsed = parse_prefix(cidr)
conn = get_db_connection()
try:
conn.execute(
"INSERT INTO prefixes (family, cidr, notes, created_at) VALUES (?, ?, ?, ?)",
(parsed["family"], parsed["cidr"], notes, datetime.utcnow().isoformat()),
)
conn.commit()
except sqlite3.IntegrityError:
conn.close()
return jsonify({"error": "El prefijo ya existe"}), 409
conn.close()
return jsonify({"status": "ok", "prefix": parsed}), 201
@app.post("/api/firewall/block")
def api_block():
payload = request.get_json(force=True)
target = str(payload.get("target", "")).strip()
scope = str(payload.get("scope", "global") or "global").strip()
reason = str(payload.get("reason", "")).strip()
normalized = validate_target(target)
conn = get_db_connection()
conn.execute(
"INSERT INTO firewall_rules (action, target, scope, reason, created_at) VALUES (?, ?, ?, ?, ?)",
("block", normalized, scope, reason, datetime.utcnow().isoformat()),
)
conn.commit()
conn.close()
return jsonify({"status": "blocked", "target": normalized, "scope": scope})
@app.post("/api/firewall/unblock")
def api_unblock():
payload = request.get_json(force=True)
target = str(payload.get("target", "")).strip()
normalized = validate_target(target)
conn = get_db_connection()
conn.execute(
"INSERT INTO firewall_rules (action, target, scope, reason, created_at) VALUES (?, ?, 'global', ?)",
("unblock", normalized, payload.get("reason", "")),
)
conn.commit()
conn.close()
return jsonify({"status": "unblocked", "target": normalized})
return app
app = create_app()
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0")