Created
March 24, 2024 09:06
SSH HTTPS Port forwarding python3 asyncio selectors security
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 2024-03-24 Gerben Aaltink | |
# Application for hosting both HTTPS and SSH on port 443 | |
# Benefits: | |
# - port 443 is allowed in any network | |
# - port hiding for hackers | |
import asyncio | |
LISTEN_PORT = 443 | |
LISTEN_HOST = '0.0.0.0' | |
SSH_FORWARD_TO_HOST = '127.0.0.1' | |
SSH_FORWARD_TO_PORT = 22 | |
HTTPS_FORWARD_TO_HOST = '127.0.0.1' | |
HTTPS_FORWARD_TO_PORT = 4430 | |
async def forward(reader, writer, direction): | |
while True: | |
data = await reader.read(4096) | |
if not data: | |
writer.transport.close() | |
break | |
writer.write(data) | |
async def handle_client(reader, writer): | |
addr = writer.get_extra_info('peername') | |
data = await reader.read(3) | |
if data[0:3] == b'SSH': | |
reader_up, writer_up = await asyncio.open_connection( | |
SSH_FORWARD_TO_HOST, SSH_FORWARD_TO_PORT | |
) | |
else: | |
reader_up, writer_up = await asyncio.open_connection( | |
HTTPS_FORWARD_TO_HOST, HTTPS_FORWARD_TO_PORT | |
) | |
writer_up.write(data) | |
await writer_up.drain() | |
await asyncio.gather( | |
forward(reader_up, writer), | |
forward(reader, writer_up) | |
) | |
print(addr, "closed") | |
async def main(): | |
server = await asyncio.start_server( | |
handle_client, LISTEN_HOST, LISTEN_PORT | |
) | |
addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets) | |
print(f'Serving on {addrs}') | |
async with server: | |
await server.serve_forever() | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment