Search code examples
pythonhtmlcookiescgiipv6

Collect user's IPv6 or MAC address on website hosted with Python HTTP Server with CGI


I am running a website on an internal network using Python 2.7 on Windows 7. I have a simple text form (with one hidden value: question number) where users submit their answers for a CTF competition. To prevent multiple responses from the same computer, I need to collect the client's IPv6 or MAC address. How should I accomplish that? It does not matter whether I use GET or POST method.

Here is my current script to accept responses. It is located in the cgi-bin directory.

import cgi

form = cgi.FieldStorage() 

p_number = form.getvalue('problem')
answer = form.getvalue('answer')

And here is my script to host the server.

import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()

def server(port):
    server = BaseHTTPServer.HTTPServer
    handler = CGIHTTPServer.CGIHTTPRequestHandler
    server_address = ("", port)
    httpd = server(server_address, handler)
    httpd.serve_forever()

While running the server, I can see everything that clients access and their IPs in the terminal. Is there a way to log this in a .txt file and then extract the needed values? (I know how to extract them if I would have the log) Here is the image, as you can see, I have been using bootstrap for the website. terminal
(source: googledrive.com)

I didn't want to ask too many questions, so here are some other things I would like to know: What is the best way to set and read cookies in Python CGI? Is it to use "Set cookie: x=y" or to import a Cookie module? Is there any other way?

Is there a way to block certain users? Lastly, I am not allowed to use any other modules that are not already included in Python 2.7.


Solution

  • When using CGI, the web server will pass the user's IP address to your script in the REMOTE_ADDR environment variable. So you can simply check this variable.

        remote_ip_address = os.environ['REMOTE_ADDR']
    

    A tuple containing the remote IP address and port can also be obtained from the CGIHTTPRequestHandler that you created.

        remote_ip_address_and_port = handler.client_address