Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.41 KB | None | 0 0
  1. import socket
  2. import sys
  3. import _thread
  4. import requests as re
  5.  
  6. HOST = ''
  7. PORT = int(sys.argv[1])
  8. buffer = 4096
  9. Bad_Words = ["spongebob","norrköping","paris hilton","britney spears", "norrk??ping"]
  10.  
  11. # Bad word has been found, now we've got to relocate.
  12. def redirectWebsite(conn):
  13.    print("302 Found")
  14.    relocate = "HTTP/1.1 302 Found\r\nLocation: http://www.ida.liu.se/~TDTS04/labs/2011/ass2/error2.html\r\n\r\n"
  15.    conn.sendall(relocate.encode('utf-8'))
  16.    print("relocation sent to connection stream")
  17.    #conn.close()
  18.  
  19. # Check for bad words
  20. def checkWords(conn, data):
  21.    redirect = False
  22.    for bad in Bad_Words:
  23.        if(str(data).find(bad) != -1):
  24.            redirect = True
  25.            break
  26.    if redirect:
  27.        redirectWebsite(conn)
  28.        return redirect
  29.    else:
  30.        return redirect
  31. def proxy_server(webserver, port, conn, data, addr):
  32.    try:
  33.        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Open socket to communicate with website
  34.        s.connect((webserver, port))                            # Connecting to web server with url and port nr.
  35.        print("connected to webserver")
  36.        s.sendall(data)                                         # Sends all the data we want, in multiple TCP segments if necessary
  37.        temp = re.get("http://"+webserver)                      # Get content within website, import requests
  38.        if checkWords(conn, temp.text.lower()):                 # Call to see if bad words are present in the website.
  39.                print("The content of the website was not family friendly and you have been redirected to another page.")
  40.        else:
  41.            while 1:
  42.  
  43.                reply = s.recv(buffer)                          # Recieve data we asked for, possibly in multiple loops
  44.                if len(reply) > 0:
  45.                    conn.sendall(reply)                         # Sends the data we just recieved back to the client.
  46.                    rad = float(len(reply))                     # Formating
  47.                    rad = float(rad / 1024)                     # Formating
  48.                    rad = "%.3s" % (str(rad))                   # Formating
  49.                    rad = "%s KB" % (rad)                       # Formating
  50.                    print("[*] Request diddelydone: %s => %s <= " % (str(data[0]),str(rad))) # Showing how big of a request we recieved.
  51.          
  52.        print("Proxy server finished beep boop")
  53.        s.close()                                               # Closing socket to website.
  54.        conn.close()                                          
  55.    except socket.error:
  56.            s.close()
  57.            conn.close()
  58.  
  59.  
  60.  
  61. def conn_string(conn, data, addr):
  62.    try:
  63.        # line = data.split('\n')[1]
  64.        # address = line.split(' ')[1]
  65.        # port = 80
  66.        # print(str(data))
  67.        temp1 = str(data)
  68.        line = temp1.split('\n')[0]
  69.        address = line.split(' ')[1]
  70.        http = address.find("://")
  71.  
  72.        if (http==-1):
  73.            temp = address
  74.        else:
  75.            temp = address[(http+3):]
  76.        ifport = temp.find(":")
  77.        webserver_pos = temp.find("/")
  78.        if webserver_pos == -1:
  79.            webserver_pos = len(temp)
  80.        webserver = ""
  81.        port = -1
  82.        if ifport ==-1 or webserver_pos < ifport:
  83.            port = 80
  84.            webserver = temp[:webserver_pos]
  85.        else:
  86.            port = int((temp[(ifport+1):])[:webserver_pos-ifport-1])
  87.            webserver = temp[:ifport]
  88.  
  89.        if(checkWords(conn, data.lower())):                     # Checking if HTTP GET REQUEST header has bad words
  90.             print("The content of the website was not family friendly and you have been redirected to another page.")
  91.             conn.close()                                       # If header contains bad words, close connection stream.
  92.        else:
  93.            print("We are now heading into proxy_server")
  94.            proxy_server(webserver, port, conn, data, addr)     # No bad words found, start connecting to webserver.
  95.    except Exception as e:
  96.        print(e)                                                # Prints whichever exception we had
  97.        pass                                                    # Continue as usual.
  98.  
  99. def main():
  100.    try:
  101.        serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)     # Create socket between proxy and client
  102.        print("Socket initialized")
  103.        serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  104.        print("sockopt works")
  105.        serverSocket.bind((HOST,PORT))                                      # Binds socket to localhost with chosen port.
  106.        print("Socket successfully bound")
  107.        print("We're now *BEEP BOOP* listening")
  108.        serverSocket.listen(5)                                              # Queue of how many requests whom can fit in the queue at one time.
  109.    except Exception as e:
  110.        print(e)
  111.        sys.exit()
  112.  
  113.    while 1:
  114.        try:
  115.            conn, addr = serverSocket.accept()                              # Accept returns a tuple, which is of type connection stream and host address.
  116.            data = conn.recv(buffer)                                        # Recieve HTTP GET REQUEST header, to be sent to webserver later.
  117.            _thread.start_new_thread(conn_string, (conn, data, addr))       # Starts a new thread, call to continue process.
  118.        except Exception as e:
  119.            serverSocket.close()
  120.            print(e)
  121.            sys.exit()
  122. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement