Skip to main content
  1. Posts/

Flask decorator for Netbox webhook authentication

·151 words·1 min·
Netdevops Blog Python Netbox Webhook Flask Apiflask
Maximilian Thoma
Author
Maximilian Thoma
network engineer

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)

Related

Netdevops python libraries toolbox
·1720 words·9 mins
Netdevops Blog Python Apiflask Flask Loguru Ciscoconfparse Dynaconf Pymongo Rq Netmiko Paramiko Ansible Pandas Ntc_templates Textfsm Requests
APIFlask Webhook Listener for Netbox
·258 words·2 mins
Netdevops Blog Netbox Python Api Apiflask
FLASK with LDAP Authentication against Active Directory and group authorization for specific pages
·457 words·3 mins
Netdevops Blog Python Flask Ldap Active_directory