add "peering-dir", logging,

This commit is contained in:
lare 2022-11-20 10:57:33 +01:00
parent cc8f181f24
commit bc55c5df00
6 changed files with 78 additions and 23 deletions

2
web/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
venv
backend/peerings/

View file

@ -20,6 +20,7 @@
"port": 8042, "port": 8042,
"domain": "example.org", // domain to use for kioubit verification service "domain": "example.org", // domain to use for kioubit verification service
"base-dir": "/", //optional:directury for which it is reachable (if behind some sort of reverse proxy) default "/" "base-dir": "/", //optional:directury for which it is reachable (if behind some sort of reverse proxy) default "/"
"peerings-dir": "/path/to/peering-configs/", // optional; default "$PWD/peerings", directory to save existing peerings to
"production": true, //optional, default true; "production": true, //optional, default true;
"debug-mode": false, // optional; whethet to enable debugging; default false "debug-mode": false, // optional; whethet to enable debugging; default false
"flask-secret-key": "<secret-please-replace>", // secret key for session cookies "flask-secret-key": "<secret-please-replace>", // secret key for session cookies

View file

@ -1,6 +1,6 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
import base64, os, json, time import base64, os, json, time, logging
import OpenSSL import OpenSSL
from OpenSSL.crypto import load_publickey, FILETYPE_PEM, verify, X509 from OpenSSL.crypto import load_publickey, FILETYPE_PEM, verify, X509
@ -15,20 +15,20 @@ class AuthVerifyer ():
pk_content = "" pk_content = ""
for line in pk.readlines(): for line in pk.readlines():
pk_content += line pk_content += line
print(pk_content) logging.debug(pk_content)
pkey = load_publickey(FILETYPE_PEM, pk_content) pkey = load_publickey(FILETYPE_PEM, pk_content)
self.x509 = X509() self.x509 = X509()
self.x509.set_pubkey(pkey) self.x509.set_pubkey(pkey)
print(self.x509) logging.debug(self.x509)
def verify(self, params, signature): def verify(self, params, signature):
# print(type(sig)) # logging.debug(type(sig))
#OpenSSL_verify(self.pubkey, sig #OpenSSL_verify(self.pubkey, sig
#, base64.b64decode(params), "sha512") #, base64.b64decode(params), "sha512")
sig = base64.b64decode(signature) sig = base64.b64decode(signature)
print(f"sig: {sig}") logging.info(f"sig: {sig}")
print(f"params: {params}") logging.info(f"params: {params}")
try: try:
verify(self.x509, sig, params, 'sha512') verify(self.x509, sig, params, 'sha512')
except OpenSSL.crypto.Error: except OpenSSL.crypto.Error:
@ -43,12 +43,12 @@ class AuthVerifyer ():
return False, "invalid JSON" return False, "invalid JSON"
except KeyError: except KeyError:
return False, "value not found in JSON" return False, "value not found in JSON"
print(user_data) logging.debug(user_data)
return True, user_data return True, user_data
if __name__ == "__main__": if __name__ == "__main__":
example_com_verifier = AuthVerifyer("example.com") example_com_verifier = AuthVerifyer("example.com")
print (example_com_verifier.verify( logging.info (example_com_verifier.verify(
params=b"eyJhc24iOiI0MjQyNDIzMDM1IiwidGltZSI6MTY2ODI2NjkyNiwiYWxsb3dlZDQiOiIxNzIuMjIuMTI1LjEyOFwvMjYsMTcyLjIwLjAuODFcLzMyIiwiYWxsb3dlZDYiOiJmZDYzOjVkNDA6NDdlNTo6XC80OCxmZDQyOmQ0MjpkNDI6ODE6OlwvNjQiLCJtbnQiOiJMQVJFLU1OVCIsImF1dGh0eXBlIjoibG9naW5jb2RlIiwiZG9tYWluIjoic3ZjLmJ1cmJsZS5kbjQyIn0=", params=b"eyJhc24iOiI0MjQyNDIzMDM1IiwidGltZSI6MTY2ODI2NjkyNiwiYWxsb3dlZDQiOiIxNzIuMjIuMTI1LjEyOFwvMjYsMTcyLjIwLjAuODFcLzMyIiwiYWxsb3dlZDYiOiJmZDYzOjVkNDA6NDdlNTo6XC80OCxmZDQyOmQ0MjpkNDI6ODE6OlwvNjQiLCJtbnQiOiJMQVJFLU1OVCIsImF1dGh0eXBlIjoibG9naW5jb2RlIiwiZG9tYWluIjoic3ZjLmJ1cmJsZS5kbjQyIn0=",
signature=b"MIGIAkIBAmwz3sQ1vOkH8+8e0NJ8GsUqKSaazIWmYDp60sshlTo7gCAopZOZ6/+tD6s+oEGM1i5mKGbHgK9ROATQLHxUZecCQgCa2N828uNn76z1Yg63/c7veMVIiK4l1X9TCUepJnJ3mCto+7ogCP+2vQm6GHipSNRF4wnt6tZbir0HZvrqEnRAmA==" signature=b"MIGIAkIBAmwz3sQ1vOkH8+8e0NJ8GsUqKSaazIWmYDp60sshlTo7gCAopZOZ6/+tD6s+oEGM1i5mKGbHgK9ROATQLHxUZecCQgCa2N828uNn76z1Yg63/c7veMVIiK4l1X9TCUepJnJ3mCto+7ogCP+2vQm6GHipSNRF4wnt6tZbir0HZvrqEnRAmA=="
) ) ) )

View file

@ -1,7 +1,7 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
from flask import Flask, Response, redirect, render_template, request, session, abort from flask import Flask, Response, redirect, render_template, request, session, abort
import json, os, base64 import json, os, base64, logging
from functools import wraps from functools import wraps
from ipaddress import ip_address, ip_network from ipaddress import ip_address, ip_network
import kioubit_verify import kioubit_verify
@ -16,7 +16,7 @@ class Config (dict):
if os.path.exists("./config.json"): self.configfile = "./config.json" if os.path.exists("./config.json"): self.configfile = "./config.json"
elif os.path.exists("/etc/dn42-autopeer/config.json"): self.configfile = "/etc/dn42-autopeer/config,json" elif os.path.exists("/etc/dn42-autopeer/config.json"): self.configfile = "/etc/dn42-autopeer/config,json"
else: raise FileNotFoundError("no config file found in ./config.json or /etc/dn42-autopeer/config.json") else: raise FileNotFoundError("no config file found in ./config.json or /etc/dn42-autopeer/config.json")
self.load_config() self._load_config()
self.keys = self._config.keys self.keys = self._config.keys
#self.__getitem__ = self._config.__getitem__ #self.__getitem__ = self._config.__getitem__
super().__init__(self) super().__init__(self)
@ -29,7 +29,8 @@ class Config (dict):
super().__delitem__(self,v) super().__delitem__(self,v)
def __getitem__(self, k): def __getitem__(self, k):
return self._config[k] return self._config[k]
def load_config(self):
def _load_config(self):
with open(self.configfile) as cf: with open(self.configfile) as cf:
try: try:
self._config = json.load(cf) self._config = json.load(cf)
@ -43,10 +44,58 @@ class Config (dict):
self._config["debug-mode"] = False self._config["debug-mode"] = False
if not "base-dir" in self._config: if not "base-dir" in self._config:
self._config["base-dir"] = "/" self._config["base-dir"] = "/"
print(self._config)
if not "peerings-data" in self._config:
self._config["peering-data"] = "./peerings"
logging.info(self._config)
class PeeringManager(dict):
def __init__(self, peering_dir):
self._peering_dir = peering_dir
self._load_peerings()
self.keys = self._peerings
def __contains__(self, o):
return self._peerings.__contains__(o)
def __getitem__(self, k):
return self._peerings[k]
def __setitem__(self, k, v):
pass
def __delitem__(self, v):
pass
def _load_peerings(self):
if not os.path.exists(self._peering_dir):
os.mkdir(self._peering_dir)
if not os.path.exists(f"{self._peering_dir}/peerings.json"):
with open(f"{self._peering_dir}/peerings.json", "x") as p:
json.dump([], p)
with open(f"{self._peering_dir}/peerings.json","r") as p:
self._peerings = json.load(p)
self.peerings = {}
missing_peerings = False
for peering in self._peerings:
if os.path.exists(f"{self._peering_dir}/{peering}.json"):
with open(f"{self._peering_dir}/{peering}.json") as peer_cfg:
self.peerings[peering] = json.load(peer_cfg)
else:
logging.warning(f"peering with id {peering} doesn't exist. removing reference in `{self._peering_dir}/peerings.json`")
self._peerings.remove(peering)
missing_peerings = True
if missing_peerings:
with open(f"{self._peering_dir}/peerings.json","w") as p:
json.dump(self._peerings, p, indent=4)
def get_peerings_by_mnt(self, mnt):
raise NotImplementedError()
config = Config() config = Config()
peerings = PeeringManager(config["peering-dir"])
def auth_required(): def auth_required():
def wrapper(f): def wrapper(f):
@wraps(f) @wraps(f)
@ -70,8 +119,8 @@ def kioubit_auth():
success, msg = kverifyer.verify(params, signature) success, msg = kverifyer.verify(params, signature)
try: print(base64.b64decode(params)) try: logging.debug(base64.b64decode(params))
except: print("invalid Base64 data provided") except: logging.debug("invalid Base64 data provided")
if success: if success:
@ -156,9 +205,11 @@ def main():
app.template_folder=config["flask-template-dir"] app.template_folder=config["flask-template-dir"]
app.secret_key = config["flask-secret-key"] app.secret_key = config["flask-secret-key"]
if "production" in config and config["production"] == False: if "production" in config and config["production"] == False:
logging.getLogger(__name__).setLevel(logging.INFO)
app.run(host=config["listen"], port=config["port"], debug=config["debug-mode"], threaded=True) app.run(host=config["listen"], port=config["port"], debug=config["debug-mode"], threaded=True)
else: else:
from waitress import serve from waitress import serve
logging.getLogger(__name__).setLevel(logging.NOTSET)
serve(app, host=config["listen"], port=config["port"]) serve(app, host=config["listen"], port=config["port"])

View file

@ -2,7 +2,7 @@
{% block content %} {% block content %}
<form action="peer" method="post"> <form action="" method="post">
<select name="node" id="node"> <select name="node" id="node">
{% for node in config["nodes"] %} {% for node in config["nodes"] %}
<option value="{{node}}" {% if selected_node %}{% if selected_node == node %}selected{% endif %}{% endif %} >{{node}}</option> <option value="{{node}}" {% if selected_node %}{% if selected_node == node %}selected{% endif %}{% endif %} >{{node}}</option>

View file

@ -1,13 +1,14 @@
{% extends 'base.html' %} {% extends 'base.html' %}
{% block content %} {% block content %}
<script>
<form action="peer" method="post"> </script>
<select name="node" id="node"> <div>
{% for node in config["nodes"] %} <a href="peerings/new"><button>add new</button></a>
<option value="{{node}}" {% if selected_node %}{% if selected_node == node %}selected{% endif %}{% endif %} >{{node}}</option> </div>
{% endfor %} <div>
</select>
</form> </div>
{% endblock %} {% endblock %}