├── .gitattributes ├── .gitignore ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── LICENSE ├── Procfile ├── Readme.md ├── assets ├── proxy-illustration.jpg └── screenshot.png ├── requirements.txt └── src └── server.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # misc 78 | .DS_Store 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 88 | .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # celery beat schedule file 98 | celerybeat-schedule 99 | 100 | # SageMath parsed files 101 | *.sage.py 102 | 103 | # Environments 104 | .env 105 | .venv 106 | env/ 107 | venv/ 108 | ENV/ 109 | env.bak/ 110 | venv.bak/ 111 | 112 | # Spyder project settings 113 | .spyderproject 114 | .spyproject 115 | 116 | # Rope project settings 117 | .ropeproject 118 | 119 | # mkdocs documentation 120 | /site 121 | 122 | # mypy 123 | .mypy_cache/ 124 | .dmypy.json 125 | dmypy.json 126 | 127 | # Pyre type checker 128 | .pyre/ 129 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | anapeksha.mukherjee@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8 2 | 3 | RUN mkdir /app 4 | 5 | WORKDIR /app 6 | 7 | COPY requirements.txt . 8 | 9 | ENV PORT=8000 10 | 11 | EXPOSE 8000 12 | 13 | RUN pip install -r requirements.txt 14 | 15 | COPY src/ . 16 | 17 | CMD [ "python", "./server.py", "--max_conn=10", "--buffer_size=8192"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Anapeksha Mukherjee 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | worker: python ./src/server.py --max_conn=10 --buffer_size=8192 -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Forward proxy server 2 | 3 | ## Introduction 4 | In computer networks, A proxy server is a server ( A computer system or 5 | an application ) that acts as an intermediary for requests from clients 6 | seeking resources from other servers. A client connects to the proxy 7 | server, requesting some service, such as a file, connection, web page, 8 | or other resource available from a different server and the proxy server 9 | evaluates the request as a way to simplify and control its complexity. 10 | 11 | Proxies were invented to add structure and encapsulation to distributed 12 | systems. Today, most proxies are web proxies, facilitating access to 13 | content on the World Wide Web and providing anonymity. 14 | 15 | ### illustration 16 |

17 | Basic proxy understanding 18 |

19 | What Bob thinks is the server ( i.e the proxy ) asked for the current time, But what Bob didn't know was, Alice asked for the current time but through the proxy server. The proxy server returns the current time to Alice. So we can basically say, Server Bob has been tricked. The proxy server acts as a man in the middle serving two people without revealing their identities to each other, Each person sees only the proxy but not the other end. 20 | 21 | Uses: 22 | 1. Filtering of encrypted data 23 | 2. Bypassing filters and censorship 24 | 3. Logging and eavesdropping 25 | 4. Improving performance 26 | 5. Security 27 | 6. Cross-domain resources 28 | 7. Translation 29 | 8. Anonymity 30 | 31 | ## Run 32 | 33 | * Bare Metal 34 | 35 | ``` 36 | python3 src/server.py --max_conn=10 --buffer_size=8192 37 | ``` 38 | 39 | * Container 40 | 41 | ``` 42 | docker run -p 8000:5000 -it python-proxy-server 43 | ``` 44 | ## Screenshot 45 |

46 | screenshot 47 |

48 | 49 | ## Deployment 50 | Can be deployed on [Heroku](https://www.heroku.com) using official [Python buildpack](https://github.com/heroku/heroku-buildpack-python) and [QuotaGuard Static](https://elements.heroku.com/addons/quotaguardstatic) add-on for a static runtime environment. 51 | 52 | ## Setup and Testing 53 | If running the proxy on your local machine with the above example, point your proxy to; 54 | ```localhost 8000``` 55 | 56 | Test access to a HTTP only webpage such as; 57 | ```http://neverssl.com``` 58 | 59 | NB: This proxy only works with HTTP connections, HTTPS will not work. -------------------------------------------------------------------------------- /assets/proxy-illustration.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anapeksha/python-proxy-server/34a1bf9106f4fea1088df4098c8cf3c929e7f67a/assets/proxy-illustration.jpg -------------------------------------------------------------------------------- /assets/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anapeksha/python-proxy-server/34a1bf9106f4fea1088df4098c8cf3c929e7f67a/assets/screenshot.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-decouple 2 | -------------------------------------------------------------------------------- /src/server.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import socket 3 | import sys 4 | from _thread import * 5 | 6 | from decouple import config 7 | 8 | try: 9 | listening_port = config('PORT', cast=int) 10 | except KeyboardInterrupt: 11 | print("\n[*] User has requested an interrupt") 12 | print("[*] Application Exiting.....") 13 | sys.exit() 14 | 15 | parser = argparse.ArgumentParser() 16 | 17 | parser.add_argument('--max_conn', help="Maximum allowed connections", default=5, type=int) 18 | parser.add_argument('--buffer_size', help="Number of samples to be used", default=8192, type=int) 19 | 20 | args = parser.parse_args() 21 | max_connection = args.max_conn 22 | buffer_size = args.buffer_size 23 | 24 | def start(): #Main Program 25 | try: 26 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 27 | sock.bind(('', listening_port)) 28 | sock.listen(max_connection) 29 | print("[*] Server started successfully [ %d ]" %(listening_port)) 30 | except Exception as e: 31 | print("[*] Unable to Initialize Socket") 32 | print(e) 33 | sys.exit(2) 34 | 35 | while True: 36 | try: 37 | conn, addr = sock.accept() #Accept connection from client browser 38 | data = conn.recv(buffer_size) #Recieve client data 39 | start_new_thread(conn_string, (conn,data, addr)) #Starting a thread 40 | except KeyboardInterrupt: 41 | sock.close() 42 | print("\n[*] Graceful Shutdown") 43 | sys.exit(1) 44 | 45 | def conn_string(conn, data, addr): 46 | try: 47 | print(data) 48 | first_line = data.split(b'\n')[0] 49 | 50 | url = first_line.split()[1] 51 | 52 | http_pos = url.find(b'://') #Finding the position of :// 53 | if(http_pos==-1): 54 | temp=url 55 | else: 56 | 57 | temp = url[(http_pos+3):] 58 | 59 | port_pos = temp.find(b':') 60 | 61 | webserver_pos = temp.find(b'/') 62 | if webserver_pos == -1: 63 | webserver_pos = len(temp) 64 | webserver = "" 65 | port = -1 66 | if(port_pos == -1 or webserver_pos < port_pos): 67 | port = 80 68 | webserver = temp[:webserver_pos] 69 | else: 70 | port = int((temp[(port_pos+1):])[:webserver_pos-port_pos-1]) 71 | webserver = temp[:port_pos] 72 | print(data) 73 | proxy_server(webserver, port, conn, addr, data) 74 | except Exception: 75 | pass 76 | 77 | def proxy_server(webserver, port, conn, addr, data): 78 | try: 79 | print(data) 80 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 81 | sock.connect((webserver, port)) 82 | sock.send(data) 83 | 84 | while 1: 85 | reply = sock.recv(buffer_size) 86 | if(len(reply)>0): 87 | conn.send(reply) 88 | 89 | dar = float(len(reply)) 90 | dar = float(dar/1024) 91 | dar = "%.3s" % (str(dar)) 92 | dar = "%s KB" % (dar) 93 | print("[*] Request Done: %s => %s <=" % (str(addr[0]), str(dar))) 94 | 95 | else: 96 | break 97 | 98 | sock.close() 99 | 100 | conn.close() 101 | except socket.error: 102 | sock.close() 103 | conn.close() 104 | print(sock.error) 105 | sys.exit(1) 106 | 107 | 108 | 109 | if __name__== "__main__": 110 | start() 111 | --------------------------------------------------------------------------------