Webhook Mini-Server

I have an application that only allows alerting over a HTTP-Post request, without any specification over the body, headers, etc. This does not work for us. We need more flexibility. So I created a simple python script, that starts a webserver, which than runs bash scripts/local commands. Simple, not too secure (but it will only run locally), and working.

What it does:
If you request the url “http://localhost:1500/my-script.sh?port=1234&hostname=example.com”, it will run the command:
/opt/webhooks/my-script.sh --port 1234 --hostname example.com

Real stupid, but it works. Use at your own risk, I’m not at fault if you do stupid shit.

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import subprocess
from os.path import isfile

pathToSearch = "/opt/webhooks"
portToBind = 1500
hostToBind = "localhost"

class RequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        return self.handleRequest()
    def do_GET(self):
        return self.handleRequest()


    def handleRequest(self):
        url_parts = urlparse(self.path)
        path = url_parts.path[1:]
        query_params = parse_qs(url_parts.query)

        filePath = '%s/%s' % (pathToSearch, path)
        
        if(isfile(filePath)):
            params = [filePath]
            for queryKey in query_params:
                for queryValue in query_params[queryKey]:
                    params += ['--%s' % queryKey, queryValue]

            subprocess.run(params) 
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b'done')
        else:
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b'not found')

            
def run_server():
    server_address = (hostToBind, portToBind)
    httpd = HTTPServer(server_address, RequestHandler)
    httpd.serve_forever()

run_server()

And a service file to accompany it:

[Unit]
Description=A webhook mini server - this is a crime

[Service]
ExecStart=/usr/bin/python3 /opt/webhooks.py
Environment=PYTHONUNBUFFERED=1
Restart=on-failure

[Install]
WantedBy=default.target

Leave a Reply

Your email address will not be published. Required fields are marked *