Today, I am excited to share with you a decorator for Flask/APIFlask, specifically designed for Netbox webhook authentication. Although I have released this in the past, this time it is available as a decorator.
import hmac
from functools import wraps
from flask import request, current_app, abort
def check_netbox_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
x_hook_signature = request.headers.get('X-Hook-Signature', None)
content_length = int(request.headers.get('Content-Length', 0))
if content_length > 1_000_000:
# To prevent memory allocation attacks
abort(400, "Content too long")
if x_hook_signature:
# Check signature
raw_input = request.data
input_hmac = hmac.new(key=current_app.config['NETBOX_SECRET'].encode(), msg=raw_input, digestmod="sha512")
if not hmac.compare_digest(input_hmac.hexdigest(), x_hook_signature):
abort(400, "Invalid message signature")
else:
abort(400, "No message signature to check")
return f(*args, **kwargs)
return decorated
You can use this in your flask app like this:
from flask import Flask, request
from netbox_wrapper import check_netbox_auth
app = Flask(__name__)
# define your shared secret
app.config['NETBOX_SECRET'] = "secret"
@app.route("/netbox_webhook", methods=['POST'])
@check_netbox_auth
def netbox_hook():
print(request.json)
return {"status":"ok"}
if __name__ == "__main__":
app.run(host='0.0.0.0', port=6666)