Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
chatroom.db
__pycache__/
.venv/
*.pem
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,16 @@ A simple chat app written in Python. Users sign up, add friends and send each ot
## Requirements

- Python 3.12 or newer
- OpenSSL, to make the certificate (Git for Windows includes it)

## How to run

Make a certificate (only once):

```
python make_cert.py
```

Start the server:

```
Expand All @@ -32,7 +39,8 @@ python main.py
## Good to know

- To start over with an empty database, run `python initialize_db.py`.
- Messages are not encrypted. Use it only on a network you trust.
- The connection is encrypted with TLS. The app only talks to a server whose certificate matches `cert.pem`.
- To chat across machines, run `python make_cert.py --host <server address>`, start the server with `--host 0.0.0.0`, and give each user a copy of `cert.pem` (never `key.pem`). They start the app with `--host <server address>`.

## For developers

Expand Down
25 changes: 16 additions & 9 deletions client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,22 @@
import threading
import traceback
from datetime import UTC, datetime
from pathlib import Path
from tkinter import *
from tkinter import messagebox

import tls

DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 5557
DEFAULT_CAFILE = Path(__file__).with_name("cert.pem")


class ServerConnection:
def __init__(self, host, port, events):
self.sock = socket.create_connection((host, port), timeout=5)
self.sock.settimeout(None)
def __init__(self, host, port, cafile, events):
context = tls.client_context(cafile)
sock = socket.create_connection((host, port), timeout=5)
self.sock = tls.LockedSocket(context.wrap_socket(sock, server_hostname=host))
self.events = events
threading.Thread(target=self._read_loop, daemon=True).start()

Expand All @@ -24,7 +29,7 @@ def send(self, type_, /, **fields):

def _read_loop(self):
try:
with self.sock.makefile("r", encoding="utf-8", errors="replace", newline="\n") as reader:
with self.sock.makefile() as reader:
for line in reader:
try:
message = json.loads(line)
Expand All @@ -37,10 +42,6 @@ def _read_loop(self):
self.events.put((self, {"type": "disconnected"}))

def close(self):
try:
self.sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
self.sock.close()


Expand All @@ -59,8 +60,11 @@ def connect_to_server():
if server:
return True
try:
server = ServerConnection(args.host, args.port, events)
server = ServerConnection(args.host, args.port, args.cafile, events)
return True
except FileNotFoundError:
messagebox.showerror("Connection Error", f"Certificate {args.cafile} not found. Ask the server owner for it.")
return False
except OSError as e:
messagebox.showerror("Connection Error", f"Failed to connect to server: {e}")
return False
Expand Down Expand Up @@ -442,6 +446,9 @@ def info():
parser = argparse.ArgumentParser(description="Run the chat client.")
parser.add_argument("--host", default=DEFAULT_HOST)
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
parser.add_argument(
"--cafile", default=DEFAULT_CAFILE, help="server certificate to trust (default: cert.pem next to this script)"
)
args = parser.parse_args()

root = Tk()
Expand Down
88 changes: 88 additions & 0 deletions make_cert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import argparse
import ipaddress
import re
import shutil
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
HOSTNAME_RE = re.compile(r"[A-Za-z0-9-]{1,63}(\.[A-Za-z0-9-]{1,63})*")
GIT_OPENSSL = [
Path(r"C:\Program Files\Git\mingw64\bin\openssl.exe"),
Path(r"C:\Program Files\Git\usr\bin\openssl.exe"),
]


def find_openssl():
found = shutil.which("openssl")
if found:
return found
for path in GIT_OPENSSL:
if path.is_file():
return str(path)
raise FileNotFoundError("openssl not found. Install OpenSSL, or Git for Windows which includes it.")


def san_entry(host):
try:
ipaddress.ip_address(host)
except ValueError:
if len(host) > 253 or not HOSTNAME_RE.fullmatch(host):
raise ValueError(f"Not a hostname or IP address: {host!r}") from None
return f"DNS:{host}"
return f"IP:{host}"


def make_cert(cert, key, hosts=(), days=365):
hosts = ["localhost", "127.0.0.1", *hosts]
san = ",".join(san_entry(host) for host in dict.fromkeys(hosts))
subprocess.run(
[
find_openssl(),
"req",
"-x509",
"-newkey",
"ec",
"-pkeyopt",
"ec_paramgen_curve:P-256",
"-nodes",
"-days",
str(days),
"-subj",
"/CN=localhost",
"-addext",
f"subjectAltName={san}",
"-keyout",
str(key),
"-out",
str(cert),
],
check=True,
capture_output=True,
)


def main():
parser = argparse.ArgumentParser(description="Make cert.pem and key.pem for the chat server.")
parser.add_argument(
"--host",
action="append",
default=[],
help="extra hostname or IP address the server is reached at (repeatable)",
)
parser.add_argument("--days", type=int, default=365)
args = parser.parse_args()
cert, key = HERE / "cert.pem", HERE / "key.pem"
try:
make_cert(cert, key, args.host, args.days)
except (FileNotFoundError, ValueError) as e:
sys.exit(str(e))
except subprocess.CalledProcessError as e:
sys.exit(f"openssl failed:\n{e.stderr.decode(errors='replace')}")
print(f"Wrote {cert} and {key}.")
print("Clients on other machines need a copy of cert.pem. Keep key.pem private.")


if __name__ == "__main__":
main()
41 changes: 30 additions & 11 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@
import queue
import re
import socket
import ssl
import sys
import threading
from pathlib import Path

import chatroom_db as db
import tls

DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 5557
DEFAULT_CERT = Path(__file__).with_name("cert.pem")
DEFAULT_KEY = Path(__file__).with_name("key.pem")
MAX_LINE = 64 * 1024
MAX_QUEUED = 1000
MAX_MESSAGE = 2000
Expand All @@ -34,7 +40,7 @@ class Connection:

def __init__(self, sock):
self.sock = sock
self.reader = sock.makefile("r", encoding="utf-8", errors="replace", newline="\n")
self.reader = sock.makefile()
self.outbox = queue.Queue(MAX_QUEUED)
self.writer = threading.Thread(target=self._write_loop, daemon=True)
self.writer.start()
Expand Down Expand Up @@ -83,10 +89,7 @@ def receive(self):

def shutdown(self):
# Wakes the reading thread, which then closes the connection.
try:
self.sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
self.sock.shutdown()

def close(self):
self.finish()
Expand Down Expand Up @@ -234,8 +237,15 @@ def handle_message(conn, message):
}


def handle_client(sock, addr):
conn = Connection(sock)
def handle_client(sock, addr, context):
try:
sock.settimeout(tls.HANDSHAKE_TIMEOUT)
sock = context.wrap_socket(sock, server_side=True)
except OSError as e:
print(f"TLS handshake with {addr} failed: {e}")
sock.close()
return
conn = Connection(tls.LockedSocket(sock))
try:
while (message := conn.receive()) is not None:
handlers = USER_HANDLERS if conn.username else GUEST_HANDLERS
Expand Down Expand Up @@ -264,26 +274,35 @@ def handle_client(sock, addr):
print(f"Disconnected {addr}")


def start_server(host=DEFAULT_HOST, port=DEFAULT_PORT):
def start_server(context, host=DEFAULT_HOST, port=DEFAULT_PORT):
db.init_db()
with socket.create_server((host, port)) as server:
print(f"Server listening on {host}:{port}")
print(f"Server listening on {host}:{port} (TLS)")
while True:
client_socket, addr = server.accept()
print(f"Connection from {addr}")
threading.Thread(target=handle_client, args=(client_socket, addr), daemon=True).start()
threading.Thread(target=handle_client, args=(client_socket, addr, context), daemon=True).start()


def main():
parser = argparse.ArgumentParser(description="Run the chat server.")
parser.add_argument("--host", default=DEFAULT_HOST)
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
parser.add_argument("--db", help="SQLite database file (default: chatroom.db next to this script)")
parser.add_argument("--cert", default=DEFAULT_CERT, help="TLS certificate (default: cert.pem next to this script)")
parser.add_argument("--key", default=DEFAULT_KEY, help="TLS private key (default: key.pem next to this script)")
args = parser.parse_args()
if args.db:
db.DB_PATH = args.db
for path in (args.cert, args.key):
if not Path(path).is_file():
sys.exit(f"{path} not found. Run python make_cert.py to make a certificate.")
try:
context = tls.server_context(args.cert, args.key)
except ssl.SSLError as e:
sys.exit(f"Could not load the certificate: {e}")
try:
start_server(args.host, args.port)
start_server(context, args.host, args.port)
except KeyboardInterrupt:
pass

Expand Down
27 changes: 21 additions & 6 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
import pytest

import chatroom_db as db
import make_cert
import tls

REPO = Path(__file__).resolve().parent.parent
HOST = "127.0.0.1"


@pytest.fixture
Expand All @@ -26,20 +29,30 @@ def free_port():
return s.getsockname()[1]


@pytest.fixture(scope="session")
def cert(tmp_path_factory):
folder = tmp_path_factory.mktemp("cert")
cert, key = folder / "cert.pem", folder / "key.pem"
make_cert.make_cert(cert, key)
return cert, key


@pytest.fixture
def server(tmp_path):
def server(tmp_path, cert):
"""Start server.py on a free port with its own database."""
port = free_port()
proc = subprocess.Popen(
[sys.executable, "-u", str(REPO / "server.py"), "--port", str(port), "--db", str(tmp_path / "server.db")],
[sys.executable, "-u", str(REPO / "server.py"), "--port", str(port), "--db", str(tmp_path / "server.db")]
+ ["--cert", str(cert[0]), "--key", str(cert[1])],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
context = tls.client_context(cert[0])
deadline = time.monotonic() + 10
while True:
try:
socket.create_connection(("127.0.0.1", port), timeout=1).close()
Client(port, context).close()
break
except OSError:
if time.monotonic() > deadline or proc.poll() is not None:
Expand All @@ -50,10 +63,12 @@ def server(tmp_path):
clients = []

def connect():
client = Client(port)
client = Client(port, context)
clients.append(client)
return client

connect.port = port
connect.context = context
yield connect
for client in clients:
client.close()
Expand All @@ -63,8 +78,8 @@ def connect():


class Client:
def __init__(self, port):
self.sock = socket.create_connection(("127.0.0.1", port))
def __init__(self, port, context):
self.sock = context.wrap_socket(socket.create_connection(("127.0.0.1", port), timeout=5), server_hostname=HOST)
self.buffer = b""

def send(self, type_, /, **fields):
Expand Down
Loading
Loading