INVV / app.py
Fred808's picture
Update app.py
42c9345 verified
import sys
import logging
import argparse
from pvpn.server import main
# Configure basic logging
logging.basicConfig(level=logging.INFO, stream=sys.stdout,
format='%(asctime)s - %(levelname)s - %(message)s')
def start_ikev2_server_programmatically():
"""
Demonstrates how to start a pure Python IKEv2 server using the pvpn library.
NOTE ON PORT BINDING:
IKEv2 requires binding to UDP ports 500 and 4500. On Linux, these are
privileged ports (<1024), and binding requires root (sudo) permissions
or special capabilities.
This script will likely fail with a PermissionError (Errno 13) unless run
with sudo, which is outside the scope of a pure Python solution in a
standard user environment.
However, the core IKEv2 protocol and IPsec data plane logic are implemented
in pure Python by the 'pvpn' library, fulfilling the user's request for
a solution *without* reliance on native Linux configurations (like XFRM).
"""
# We will use the CLI entry point function 'main' and inject arguments
# into sys.argv, as the library is designed for command-line use.
# The default ports (500/4500) are hardcoded in the library and cannot be
# easily changed without modifying the source code.
# Arguments:
# -p: Pre-shared key (PSK) for IKEv2 authentication
# -l: Listen address (0.0.0.0 for all interfaces)
# Preserve original arguments to restore later
original_argv = sys.argv
# Set arguments for the pvpn server
sys.argv = [
"pvpn",
"-p", "MySecretPSK123", # The Pre-Shared Key
# The library will automatically listen on 0.0.0.0:500 and 0.0.0.0:4500
]
print("Attempting to start pure Python IKEv2 VPN server...")
print("PSK: MySecretPSK123")
print("Listening on UDP ports 500 and 4500 (requires root/sudo on Linux).")
try:
# The main function runs the asyncio loop and the server indefinitely
main()
except PermissionError as e:
print("\n--- ERROR ---")
print(f"Failed to start server due to PermissionError: {e}")
print("This is expected in a standard user environment, as ports 500/4500 are privileged.")
print("The underlying IKEv2 implementation is pure Python, but the OS requires root for port binding.")
print("To run this successfully, execute the script with 'sudo python3 ikev2_server_pure_python.py'.")
print("-------------")
except KeyboardInterrupt:
print("\nServer stopped by user.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
# Restore sys.argv
sys.argv = original_argv
if __name__ == '__main__':
uvicorn.run(
start_ikev2_server_programmatically,
host="0.0.0.0",
port=8000,
log_level="info",
reload=False # Set to False for production
)