mirror of
https://github.com/donaldzou/WGDashboard.git
synced 2025-10-03 15:56:17 +00:00
v2.2 beta 4
This commit is contained in:
259
src/dashboard.py
259
src/dashboard.py
@@ -23,13 +23,13 @@ dashboard_version = 'v2.2'
|
||||
dashboard_conf = 'wg-dashboard.ini'
|
||||
# Default Wireguard IP
|
||||
wg_ip = ifcfg.default_interface()['inet']
|
||||
|
||||
# Upgrade Required
|
||||
update = ""
|
||||
# Flask App Configuration
|
||||
app = Flask("Wireguard Dashboard")
|
||||
app.secret_key = secrets.token_urlsafe(16)
|
||||
app.config['TEMPLATES_AUTO_RELOAD'] = True
|
||||
# Enable QR Code Generator
|
||||
QRcode(app)
|
||||
|
||||
|
||||
@@ -39,7 +39,8 @@ def get_conf_peer_key(config_name):
|
||||
peer_key = peer_key.decode("UTF-8").split()
|
||||
return peer_key
|
||||
except Exception:
|
||||
return config_name+" is not running."
|
||||
return config_name + " is not running."
|
||||
|
||||
|
||||
def get_conf_running_peer_number(config_name):
|
||||
running = 0
|
||||
@@ -59,10 +60,12 @@ def get_conf_running_peer_number(config_name):
|
||||
count += 2
|
||||
return running
|
||||
|
||||
|
||||
def is_match(regex, text):
|
||||
pattern = re.compile(regex)
|
||||
return pattern.search(text) is not None
|
||||
|
||||
|
||||
def read_conf_file(config_name):
|
||||
# Read Configuration File Start
|
||||
conf_location = wg_conf_path + "/" + config_name + ".conf"
|
||||
@@ -74,7 +77,7 @@ def read_conf_file(config_name):
|
||||
}
|
||||
peers_start = 0
|
||||
for i in range(len(file)):
|
||||
if not is_match("#(.*)",file[i]):
|
||||
if not is_match("#(.*)", file[i]):
|
||||
if file[i] == "[Peer]":
|
||||
peers_start = i
|
||||
break
|
||||
@@ -101,6 +104,7 @@ def read_conf_file(config_name):
|
||||
# Read Configuration File End
|
||||
return conf_peer_data
|
||||
|
||||
|
||||
def get_latest_handshake(config_name, db, peers):
|
||||
# Get latest handshakes
|
||||
try:
|
||||
@@ -124,6 +128,7 @@ def get_latest_handshake(config_name, db, peers):
|
||||
db.update({"latest_handshake": "(None)", "status": status}, peers.id == data_usage[count])
|
||||
count += 2
|
||||
|
||||
|
||||
def get_transfer(config_name, db, peers):
|
||||
# Get transfer
|
||||
try:
|
||||
@@ -158,6 +163,7 @@ def get_transfer(config_name, db, peers):
|
||||
|
||||
count += 3
|
||||
|
||||
|
||||
def get_endpoint(config_name, db, peers):
|
||||
# Get endpoint
|
||||
try:
|
||||
@@ -170,12 +176,14 @@ def get_endpoint(config_name, db, peers):
|
||||
db.update({"endpoint": data_usage[count + 1]}, peers.id == data_usage[count])
|
||||
count += 2
|
||||
|
||||
|
||||
def get_allowed_ip(config_name, db, peers, conf_peer_data):
|
||||
# Get allowed ip
|
||||
for i in conf_peer_data["Peers"]:
|
||||
db.update({"allowed_ip": i.get('AllowedIPs', '(None)')}, peers.id == i["PublicKey"])
|
||||
|
||||
def get_conf_peers_data(config_name):
|
||||
|
||||
def get_all_peers_data(config_name):
|
||||
db = TinyDB('db/' + config_name + '.json')
|
||||
peers = Query()
|
||||
conf_peer_data = read_conf_file(config_name)
|
||||
@@ -186,7 +194,8 @@ def get_conf_peers_data(config_name):
|
||||
db.insert({
|
||||
"id": i['PublicKey'],
|
||||
"private_key": "",
|
||||
"DNS":"1.1.1.1",
|
||||
"DNS": "1.1.1.1",
|
||||
"endpoint_allowed_ip":"0.0.0.0/0",
|
||||
"name": "",
|
||||
"total_receive": 0,
|
||||
"total_sent": 0,
|
||||
@@ -204,6 +213,8 @@ def get_conf_peers_data(config_name):
|
||||
update_db['private_key'] = ''
|
||||
if "DNS" not in search[0]:
|
||||
update_db['DNS'] = '1.1.1.1'
|
||||
if "endpoint_allowed_ip" not in search[0]:
|
||||
update_db['endpoint_allowed_ip'] = '0.0.0.0/0'
|
||||
db.update(update_db, peers.id == i['PublicKey'])
|
||||
|
||||
tic = time.perf_counter()
|
||||
@@ -215,14 +226,21 @@ def get_conf_peers_data(config_name):
|
||||
print(f"Finish fetching data in {toc - tic:0.4f} seconds")
|
||||
db.close()
|
||||
|
||||
def get_peers(config_name):
|
||||
get_conf_peers_data(config_name)
|
||||
|
||||
def get_peers(config_name, search, sort_t):
|
||||
get_all_peers_data(config_name)
|
||||
db = TinyDB('db/' + config_name + '.json')
|
||||
result = db.all()
|
||||
result = sorted(result, key=lambda d: d['status'])
|
||||
peer = Query()
|
||||
print(search)
|
||||
if len(search) == 0:
|
||||
result = db.all()
|
||||
else:
|
||||
result = db.search(peer.name.matches('(.*)(' + re.escape(search) + ')(.*)'))
|
||||
result = sorted(result, key=lambda d: d[sort_t])
|
||||
db.close()
|
||||
return result
|
||||
|
||||
|
||||
def get_conf_pub_key(config_name):
|
||||
conf = configparser.ConfigParser(strict=False)
|
||||
conf.read(wg_conf_path + "/" + config_name + ".conf")
|
||||
@@ -231,6 +249,7 @@ def get_conf_pub_key(config_name):
|
||||
conf.clear()
|
||||
return pub.decode().strip("\n")
|
||||
|
||||
|
||||
def get_conf_listen_port(config_name):
|
||||
conf = configparser.ConfigParser(strict=False)
|
||||
conf.read(wg_conf_path + "/" + config_name + ".conf")
|
||||
@@ -238,6 +257,7 @@ def get_conf_listen_port(config_name):
|
||||
conf.clear()
|
||||
return port
|
||||
|
||||
|
||||
def get_conf_total_data(config_name):
|
||||
db = TinyDB('db/' + config_name + '.json')
|
||||
upload_total = 0
|
||||
@@ -254,6 +274,7 @@ def get_conf_total_data(config_name):
|
||||
db.close()
|
||||
return [total, upload_total, download_total]
|
||||
|
||||
|
||||
def get_conf_status(config_name):
|
||||
ifconfig = dict(ifcfg.interfaces().items())
|
||||
if config_name in ifconfig.keys():
|
||||
@@ -261,6 +282,7 @@ def get_conf_status(config_name):
|
||||
else:
|
||||
return "stopped"
|
||||
|
||||
|
||||
def get_conf_list():
|
||||
conf = []
|
||||
for i in os.listdir(wg_conf_path):
|
||||
@@ -276,6 +298,7 @@ def get_conf_list():
|
||||
conf = sorted(conf, key=itemgetter('conf'))
|
||||
return conf
|
||||
|
||||
|
||||
def genKeys():
|
||||
gen = subprocess.check_output('wg genkey > private_key.txt && wg pubkey < private_key.txt > public_key.txt',
|
||||
shell=True)
|
||||
@@ -290,6 +313,7 @@ def genKeys():
|
||||
os.remove('public_key.txt')
|
||||
return data
|
||||
|
||||
|
||||
def genPubKey(private_key):
|
||||
pri_key_file = open('private_key.txt', 'w')
|
||||
pri_key_file.write(private_key)
|
||||
@@ -300,10 +324,11 @@ def genPubKey(private_key):
|
||||
public_key = public.readline().strip()
|
||||
os.remove('private_key.txt')
|
||||
os.remove('public_key.txt')
|
||||
return {"status":'success', "msg":"", "data":public_key}
|
||||
return {"status": 'success', "msg": "", "data": public_key}
|
||||
except subprocess.CalledProcessError as exc:
|
||||
os.remove('private_key.txt')
|
||||
return {"status":'failed', "msg":"Key is not the correct length or format", "data":""}
|
||||
return {"status": 'failed', "msg": "Key is not the correct length or format", "data": ""}
|
||||
|
||||
|
||||
def checkKeyMatch(private_key, public_key, config_name):
|
||||
result = genPubKey(private_key)
|
||||
@@ -318,6 +343,7 @@ def checkKeyMatch(private_key, public_key, config_name):
|
||||
else:
|
||||
return {'status': 'success'}
|
||||
|
||||
|
||||
def checkAllowedIP(public_key, ip, config_name):
|
||||
db = TinyDB('db/' + config_name + '.json')
|
||||
peers = Query()
|
||||
@@ -327,9 +353,26 @@ def checkAllowedIP(public_key, ip, config_name):
|
||||
else:
|
||||
existed_ip = db.search((peers.id != public_key) & (peers.allowed_ip == ip))
|
||||
if len(existed_ip) != 0:
|
||||
return {'status':'failed', 'msg':"Allowed IP already taken by another peer."}
|
||||
return {'status': 'failed', 'msg': "Allowed IP already taken by another peer."}
|
||||
else:
|
||||
return {'status':'success'}
|
||||
return {'status': 'success'}
|
||||
|
||||
def checkIp(ip):
|
||||
return is_match("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}",ip)
|
||||
def cleanIp(ip):
|
||||
return ip.replace(' ','')
|
||||
def cleanIpWithRange(ip):
|
||||
return cleanIp(ip).split(',')
|
||||
def checkIpWithRange(ip):
|
||||
return is_match("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|\/)){4}(0|8|16|24|32)(,|$)", ip)
|
||||
def checkAllowedIPs(ip):
|
||||
ip = cleanIpWithRange(ip)
|
||||
for i in ip:
|
||||
if not checkIpWithRange(i): return False
|
||||
return True
|
||||
|
||||
|
||||
|
||||
|
||||
@app.before_request
|
||||
def auth_req():
|
||||
@@ -344,7 +387,7 @@ def auth_req():
|
||||
request.endpoint != "signout" and \
|
||||
request.endpoint != "auth" and \
|
||||
"username" not in session:
|
||||
print("User not loggedin - Attemped access: "+str(request.endpoint))
|
||||
print("User not loggedin - Attemped access: " + str(request.endpoint))
|
||||
if request.endpoint != "index":
|
||||
session['message'] = "You need to sign in first!"
|
||||
else:
|
||||
@@ -387,7 +430,9 @@ def settings():
|
||||
required_auth = config.get("Server", "auth_req")
|
||||
return render_template('settings.html', conf=get_conf_list(), message=message, status=status,
|
||||
app_ip=config.get("Server", "app_ip"), app_port=config.get("Server", "app_port"),
|
||||
required_auth=required_auth, wg_conf_path=config.get("Server", "wg_conf_path"))
|
||||
required_auth=required_auth, wg_conf_path=config.get("Server", "wg_conf_path"),
|
||||
peer_global_DNS=config.get("Peers","peer_global_DNS"),
|
||||
peer_endpoint_allowed_ip=config.get("Peers","peer_endpoint_allowed_ip"))
|
||||
|
||||
|
||||
@app.route('/auth', methods=['POST'])
|
||||
@@ -408,6 +453,10 @@ def auth():
|
||||
|
||||
@app.route('/update_acct', methods=['POST'])
|
||||
def update_acct():
|
||||
if len(request.form['username']) == 0:
|
||||
session['message'] = "Username cannot be empty."
|
||||
session['message_status'] = "danger"
|
||||
return redirect(url_for("settings"))
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(dashboard_conf)
|
||||
config.set("Account", "username", request.form['username'])
|
||||
@@ -424,6 +473,46 @@ def update_acct():
|
||||
config.clear()
|
||||
return redirect(url_for("settings"))
|
||||
|
||||
@app.route('/update_peer_default_config', methods=['POST'])
|
||||
def update_peer_default_config():
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(dashboard_conf)
|
||||
if len(request.form['peer_endpoint_allowed_ip']) == 0 or len(request.form['peer_global_DNS']) == 0:
|
||||
session['message'] = "Peer DNS or Peer Endpoint Allowed IP cannot be empty."
|
||||
session['message_status'] = "danger"
|
||||
return redirect(url_for("settings"))
|
||||
# Check DNS Format
|
||||
DNS = request.form['peer_global_DNS']
|
||||
DNS = cleanIp(DNS)
|
||||
if not checkIp(DNS):
|
||||
session['message'] = "Peer DNS Format Incorrect. Example: 1.1.1.1"
|
||||
session['message_status'] = "danger"
|
||||
return redirect(url_for("settings"))
|
||||
|
||||
# Check Endpoint Allowed IPs
|
||||
ip = request.form['peer_endpoint_allowed_ip']
|
||||
if not checkAllowedIPs(ip):
|
||||
session['message'] = "Peer Endpoint Allowed IPs Format Incorrect. Example: 192.168.1.1/32 or 192.168.1.1/32,192.168.1.2/32"
|
||||
session['message_status'] = "danger"
|
||||
return redirect(url_for("settings"))
|
||||
|
||||
|
||||
|
||||
|
||||
config.set("Peers", "peer_endpoint_allowed_ip", ','.join(cleanIpWithRange(ip)))
|
||||
config.set("Peers", "peer_global_DNS", request.form['peer_global_DNS'])
|
||||
try:
|
||||
config.write(open(dashboard_conf, "w"))
|
||||
session['message'] = "DNS and Enpoint Allowed IP update successfully!"
|
||||
session['message_status'] = "success"
|
||||
config.clear()
|
||||
return redirect(url_for("settings"))
|
||||
except Exception:
|
||||
session['message'] = "DNS and Enpoint Allowed IP update failed."
|
||||
session['message_status'] = "danger"
|
||||
config.clear()
|
||||
return redirect(url_for("settings"))
|
||||
|
||||
|
||||
@app.route('/update_pwd', methods=['POST'])
|
||||
def update_pwd():
|
||||
@@ -478,6 +567,22 @@ def update_wg_conf_path():
|
||||
config.clear()
|
||||
os.system('bash wgd.sh restart')
|
||||
|
||||
|
||||
@app.route('/update_dashboard_sort', methods=['POST'])
|
||||
def update_dashbaord_sort():
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(dashboard_conf)
|
||||
data = request.get_json()
|
||||
sort_tag = ['name', 'status', 'allowed_ip']
|
||||
if data['sort'] in sort_tag:
|
||||
config.set("Server", "dashboard_sort", data['sort'])
|
||||
else:
|
||||
config.set("Server", "dashboard_sort", 'status')
|
||||
config.write(open(dashboard_conf, "w"))
|
||||
config.clear()
|
||||
return "true"
|
||||
|
||||
|
||||
@app.route('/update_dashboard_refresh_interval', methods=['POST'])
|
||||
def update_dashboard_refresh_interval():
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
@@ -487,28 +592,30 @@ def update_dashboard_refresh_interval():
|
||||
config.clear()
|
||||
return "true"
|
||||
|
||||
|
||||
@app.route('/get_ping_ip', methods=['POST'])
|
||||
def get_ping_ip():
|
||||
config = request.form['config']
|
||||
db = TinyDB('db/' + config + '.json')
|
||||
html = ""
|
||||
for i in db.all():
|
||||
html += '<optgroup label="'+i['name']+' - '+i['id']+'">'
|
||||
html += '<optgroup label="' + i['name'] + ' - ' + i['id'] + '">'
|
||||
allowed_ip = str(i['allowed_ip']).split(",")
|
||||
for k in allowed_ip:
|
||||
k = k.split("/")
|
||||
if len(k) == 2:
|
||||
html += "<option value="+k[0]+">"+k[0]+"</option>"
|
||||
html += "<option value=" + k[0] + ">" + k[0] + "</option>"
|
||||
endpoint = str(i['endpoint']).split(":")
|
||||
if len(endpoint) == 2:
|
||||
html += "<option value=" + endpoint[0] + ">" + endpoint[0] + "</option>"
|
||||
html += "</optgroup>"
|
||||
return html
|
||||
|
||||
|
||||
@app.route('/ping_ip', methods=['POST'])
|
||||
def ping_ip():
|
||||
try:
|
||||
result = ping(''+request.form['ip']+'', count=int(request.form['count']),privileged=True, source=None)
|
||||
result = ping('' + request.form['ip'] + '', count=int(request.form['count']), privileged=True, source=None)
|
||||
returnjson = {
|
||||
"address": result.address,
|
||||
"is_alive": result.is_alive,
|
||||
@@ -523,21 +630,24 @@ def ping_ip():
|
||||
except Exception:
|
||||
return "Error"
|
||||
|
||||
|
||||
@app.route('/traceroute_ip', methods=['POST'])
|
||||
def traceroute_ip():
|
||||
try:
|
||||
result = traceroute(''+request.form['ip']+'', first_hop=1, max_hops=30, count=1, fast=True)
|
||||
result = traceroute('' + request.form['ip'] + '', first_hop=1, max_hops=30, count=1, fast=True)
|
||||
returnjson = []
|
||||
last_distance = 0
|
||||
for hop in result:
|
||||
if last_distance + 1 != hop.distance:
|
||||
returnjson.append({"hop":"*", "ip":"*", "avg_rtt":"", "min_rtt":"", "max_rtt":""})
|
||||
returnjson.append({"hop": hop.distance, "ip": hop.address, "avg_rtt": hop.avg_rtt, "min_rtt": hop.min_rtt, "max_rtt": hop.max_rtt})
|
||||
returnjson.append({"hop": "*", "ip": "*", "avg_rtt": "", "min_rtt": "", "max_rtt": ""})
|
||||
returnjson.append({"hop": hop.distance, "ip": hop.address, "avg_rtt": hop.avg_rtt, "min_rtt": hop.min_rtt,
|
||||
"max_rtt": hop.max_rtt})
|
||||
last_distance = hop.distance
|
||||
return jsonify(returnjson)
|
||||
except Exception:
|
||||
return "Error"
|
||||
|
||||
|
||||
@app.route('/', methods=['GET'])
|
||||
def index():
|
||||
return render_template('index.html', conf=get_conf_list())
|
||||
@@ -545,6 +655,8 @@ def index():
|
||||
|
||||
@app.route('/configuration/<config_name>', methods=['GET'])
|
||||
def conf(config_name):
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(dashboard_conf)
|
||||
conf_data = {
|
||||
"name": config_name,
|
||||
"status": get_conf_status(config_name),
|
||||
@@ -559,27 +671,34 @@ def conf(config_name):
|
||||
config_list = get_conf_list()
|
||||
if config_name not in [conf['conf'] for conf in config_list]:
|
||||
return render_template('index.html', conf=get_conf_list())
|
||||
return render_template('configuration.html', conf=get_conf_list(), conf_data=conf_data, dashboard_refresh_interval=int(config.get("Server","dashboard_refresh_interval")))
|
||||
return render_template('configuration.html', conf=get_conf_list(), conf_data=conf_data,
|
||||
dashboard_refresh_interval=int(config.get("Server", "dashboard_refresh_interval")),
|
||||
DNS=config.get("Peers", "peer_global_DNS"),
|
||||
endpoint_allowed_ip=config.get("Peers", "peer_endpoint_allowed_ip"), title=config_name)
|
||||
|
||||
|
||||
@app.route('/get_config/<config_name>', methods=['GET'])
|
||||
def get_conf(config_name):
|
||||
search = request.args.get('search')
|
||||
if len(search) == 0: search = ""
|
||||
search = urllib.parse.unquote(search)
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(dashboard_conf)
|
||||
sort = config.get("Server", "dashboard_sort")
|
||||
conf_data = {
|
||||
"peer_data": get_peers(config_name),
|
||||
"peer_data": get_peers(config_name, search, sort),
|
||||
"name": config_name,
|
||||
"status": get_conf_status(config_name),
|
||||
"total_data_usage": get_conf_total_data(config_name),
|
||||
"public_key": get_conf_pub_key(config_name),
|
||||
"listen_port": get_conf_listen_port(config_name),
|
||||
"running_peer": get_conf_running_peer_number(config_name),
|
||||
|
||||
}
|
||||
if conf_data['status'] == "stopped":
|
||||
# return redirect('/')
|
||||
conf_data['checked'] = "nope"
|
||||
else:
|
||||
conf_data['checked'] = "checked"
|
||||
return render_template('get_conf.html', conf=get_conf_list(), conf_data=conf_data, wg_ip=wg_ip)
|
||||
return render_template('get_conf.html', conf_data=conf_data, wg_ip=wg_ip, sort_tag=sort, dashboard_refresh_interval=int(config.get("Server", "dashboard_refresh_interval")))
|
||||
|
||||
|
||||
@app.route('/switch/<config_name>', methods=['GET'])
|
||||
@@ -609,21 +728,30 @@ def add_peer(config_name):
|
||||
data = request.get_json()
|
||||
public_key = data['public_key']
|
||||
allowed_ips = data['allowed_ips']
|
||||
endpoint_allowed_ip = data['endpoint_allowed_ip']
|
||||
DNS = data['DNS']
|
||||
keys = get_conf_peer_key(config_name)
|
||||
if type(keys) != list:
|
||||
return config_name+" is not running."
|
||||
return config_name + " is not running."
|
||||
if public_key in keys:
|
||||
return "Public key already exist."
|
||||
if len(db.search(peers.allowed_ip.matches(allowed_ips))) != 0:
|
||||
return "Allowed IP already taken by another peer."
|
||||
if not checkIp(DNS):
|
||||
return "DNS formate is incorrect. Example: 1.1.1.1"
|
||||
|
||||
if not checkAllowedIPs(endpoint_allowed_ip):
|
||||
return "Endpoint Allowed IPs format is incorrect."
|
||||
else:
|
||||
status = ""
|
||||
try:
|
||||
status = subprocess.check_output(
|
||||
"wg set " + config_name + " peer " + public_key + " allowed-ips " + allowed_ips, shell=True, stderr=subprocess.STDOUT)
|
||||
"wg set " + config_name + " peer " + public_key + " allowed-ips " + allowed_ips, shell=True,
|
||||
stderr=subprocess.STDOUT)
|
||||
status = subprocess.check_output("wg-quick save " + config_name, shell=True, stderr=subprocess.STDOUT)
|
||||
get_conf_peers_data(config_name)
|
||||
db.update({"name": data['name'], "private_key": data['private_key'], "DNS": data['DNS']}, peers.id == public_key)
|
||||
get_all_peers_data(config_name)
|
||||
db.update({"name": data['name'], "private_key": data['private_key'], "DNS": data['DNS'], "endpoint_allowed_ip": endpoint_allowed_ip},
|
||||
peers.id == public_key)
|
||||
db.close()
|
||||
return "true"
|
||||
except subprocess.CalledProcessError as exc:
|
||||
@@ -641,7 +769,7 @@ def remove_peer(config_name):
|
||||
delete_key = data['peer_id']
|
||||
keys = get_conf_peer_key(config_name)
|
||||
if type(keys) != list:
|
||||
return config_name+" is not running."
|
||||
return config_name + " is not running."
|
||||
if delete_key not in keys:
|
||||
db.close()
|
||||
return "This key does not exist"
|
||||
@@ -665,6 +793,7 @@ def save_peer_setting(config_name):
|
||||
private_key = data['private_key']
|
||||
DNS = data['DNS']
|
||||
allowed_ip = data['allowed_ip']
|
||||
endpoint_allowed_ip = data['endpoint_allowed_ip']
|
||||
db = TinyDB("db/" + config_name + ".json")
|
||||
peers = Query()
|
||||
if len(db.search(peers.id == id)) == 1:
|
||||
@@ -679,22 +808,25 @@ def save_peer_setting(config_name):
|
||||
try:
|
||||
if allowed_ip == "":
|
||||
allowed_ip = '""'
|
||||
change_ip = subprocess.check_output('wg set '+config_name+" peer "+id+" allowed-ips "+allowed_ip, shell=True, stderr=subprocess.STDOUT)
|
||||
save_change_ip = subprocess.check_output('wg-quick save '+ config_name, shell=True,stderr=subprocess.STDOUT)
|
||||
change_ip = subprocess.check_output('wg set ' + config_name + " peer " + id + " allowed-ips " + allowed_ip,
|
||||
shell=True, stderr=subprocess.STDOUT)
|
||||
save_change_ip = subprocess.check_output('wg-quick save ' + config_name, shell=True,
|
||||
stderr=subprocess.STDOUT)
|
||||
if change_ip.decode("UTF-8") != "":
|
||||
return jsonify({"status":"failed", "msg": change_ip.decode("UTF-8")})
|
||||
return jsonify({"status": "failed", "msg": change_ip.decode("UTF-8")})
|
||||
|
||||
db.update({"name": name, "private_key": private_key, "DNS": DNS}, peers.id == id)
|
||||
|
||||
db.update({"name": name, "private_key": private_key, "DNS": DNS, "endpoint_allowed_ip":endpoint_allowed_ip}, peers.id == id)
|
||||
db.close()
|
||||
return jsonify({"status": "success", "msg": ""})
|
||||
except subprocess.CalledProcessError as exc:
|
||||
return jsonify({"status":"failed", "msg": str(exc.output.decode("UTF-8").strip())})
|
||||
return jsonify({"status": "failed", "msg": str(exc.output.decode("UTF-8").strip())})
|
||||
|
||||
|
||||
|
||||
|
||||
else:
|
||||
return jsonify({"status":"failed","msg":"This peer does not exist."})
|
||||
return jsonify({"status": "failed", "msg": "This peer does not exist."})
|
||||
|
||||
|
||||
@app.route('/get_peer_data/<config_name>', methods=['POST'])
|
||||
@@ -705,28 +837,35 @@ def get_peer_name(config_name):
|
||||
peers = Query()
|
||||
result = db.search(peers.id == id)
|
||||
db.close()
|
||||
data = {"name": result[0]['name'], "allowed_ip":result[0]['allowed_ip'], "DNS": result[0]['DNS'], "private_key": result[0]['private_key']}
|
||||
data = {"name": result[0]['name'], "allowed_ip": result[0]['allowed_ip'], "DNS": result[0]['DNS'],
|
||||
"private_key": result[0]['private_key'], "endpoint_allowed_ip": result[0]['endpoint_allowed_ip']}
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
@app.route('/generate_peer', methods=['GET'])
|
||||
def generate_peer():
|
||||
return jsonify(genKeys())
|
||||
|
||||
|
||||
@app.route('/generate_public_key', methods=['POST'])
|
||||
def generate_public_key():
|
||||
data = request.get_json()
|
||||
private_key = data['private_key']
|
||||
return jsonify(genPubKey(private_key))
|
||||
|
||||
|
||||
@app.route('/check_key_match/<config_name>', methods=['POST'])
|
||||
def check_key_match(config_name):
|
||||
data = request.get_json()
|
||||
private_key = data['private_key']
|
||||
public_key = data['public_key']
|
||||
return jsonify(checkKeyMatch(private_key,public_key, config_name))
|
||||
return jsonify(checkKeyMatch(private_key, public_key, config_name))
|
||||
|
||||
|
||||
@app.route('/download/<config_name>', methods=['GET'])
|
||||
def download(config_name):
|
||||
print(request.headers.get('User-Agent'))
|
||||
|
||||
id = request.args.get('id')
|
||||
db = TinyDB("db/" + config_name + ".json")
|
||||
peers = Query()
|
||||
@@ -738,23 +877,38 @@ def download(config_name):
|
||||
if peer['private_key'] != "":
|
||||
public_key = get_conf_pub_key(config_name)
|
||||
listen_port = get_conf_listen_port(config_name)
|
||||
endpoint = wg_ip+":"+listen_port
|
||||
endpoint = wg_ip + ":" + listen_port
|
||||
private_key = peer['private_key']
|
||||
allowed_ip = peer['allowed_ip']
|
||||
DNS = peer['DNS']
|
||||
name = "".join(peer['name'].split(' '))
|
||||
if name == "": name = public_key
|
||||
def generate(private_key, allowed_ip, DNS, public_key, endpoint):
|
||||
yield "[Interface]\nPrivateKey = "+private_key+"\nAddress = "+allowed_ip+"\nDNS = "+DNS+"\n\n[Peer]\nPublicKey = "+public_key+"\nAllowedIPs = 0.0.0.0/0\nEndpoint = "+endpoint
|
||||
|
||||
return app.response_class(generate(private_key,allowed_ip,DNS, public_key,endpoint), mimetype='text/conf', headers={"Content-Disposition":"attachment;filename="+name+".conf"})
|
||||
filename = peer['name']
|
||||
if len(filename) == 0:
|
||||
filename = "Untitled_Peers"
|
||||
else:
|
||||
filename = peer['name']
|
||||
# Clean filename
|
||||
illegal_filename = [".", ",", "/", "?", "<", ">", "\\", ":", "*", '|' '\"', "com1", "com2", "com3",
|
||||
"com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4",
|
||||
"lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "con", "nul", "prn"]
|
||||
for i in illegal_filename:
|
||||
filename = filename.replace(i, "")
|
||||
print(filename)
|
||||
if len(filename) == 0:
|
||||
filename = "Untitled_Peer"
|
||||
filename = "".join(filename.split(' '))
|
||||
filename = filename + "_" + config_name
|
||||
|
||||
def generate(private_key, allowed_ip, DNS, public_key, endpoint):
|
||||
yield "[Interface]\nPrivateKey = " + private_key + "\nAddress = " + allowed_ip + "\nDNS = " + DNS + "\n\n[Peer]\nPublicKey = " + public_key + "\nAllowedIPs = 0.0.0.0/0\nEndpoint = " + endpoint
|
||||
|
||||
return app.response_class(generate(private_key, allowed_ip, DNS, public_key, endpoint),
|
||||
mimetype='text/conf',
|
||||
headers={"Content-Disposition": "attachment;filename=" + filename + ".conf"})
|
||||
else:
|
||||
return redirect("/configuration/" + config_name)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def init_dashboard():
|
||||
# Set Default INI File
|
||||
if not os.path.isfile("wg-dashboard.ini"):
|
||||
@@ -783,6 +937,15 @@ def init_dashboard():
|
||||
config['Server']['version'] = dashboard_version
|
||||
if 'dashboard_refresh_interval' not in config['Server']:
|
||||
config['Server']['dashboard_refresh_interval'] = '15000'
|
||||
if 'dashboard_sort' not in config['Server']:
|
||||
config['Server']['dashboard_sort'] = 'status'
|
||||
|
||||
if "Peers" not in config:
|
||||
config['Peers'] = {}
|
||||
if 'peer_global_DNS' not in config['Peers']:
|
||||
config['Peers']['peer_global_DNS'] = '1.1.1.1'
|
||||
if 'peer_endpoint_allowed_ip' not in config['Peers']:
|
||||
config['Peers']['peer_endpoint_allowed_ip'] = '0.0.0.0/0'
|
||||
config.write(open(dashboard_conf, "w"))
|
||||
config.clear()
|
||||
|
||||
|
Reference in New Issue
Block a user