Skip to content

Commit 3d4a649

Browse files
committed
Fix and refactor of SSL handling for CPython
1 parent d943404 commit 3d4a649

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

adafruit_httpserver/server.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@
3434
from .route import Route
3535
from .status import BAD_REQUEST_400, UNAUTHORIZED_401, FORBIDDEN_403, NOT_FOUND_404
3636

37+
if implementation.name != "circuitpython":
38+
from ssl import Purpose, CERT_NONE, SSLError
39+
3740

3841
NO_REQUEST = "no_request"
3942
CONNECTION_TIMED_OUT = "connection_timed_out"
@@ -62,13 +65,33 @@ def _validate_https_cert_provided(certfile: str, keyfile: str) -> None:
6265
raise ValueError("Both certfile and keyfile must be specified for HTTPS")
6366

6467
@staticmethod
65-
def _create_ssl_context(certfile: str, keyfile: str) -> SSLContext:
68+
def __create_circuitpython_ssl_context(certfile: str, keyfile: str) -> SSLContext:
6669
ssl_context = create_default_context()
70+
6771
ssl_context.load_verify_locations(cadata="")
6872
ssl_context.load_cert_chain(certfile, keyfile)
6973

7074
return ssl_context
7175

76+
@staticmethod
77+
def __create_cpython_ssl_context(certfile: str, keyfile: str) -> SSLContext:
78+
ssl_context = create_default_context(purpose=Purpose.CLIENT_AUTH)
79+
80+
ssl_context.load_cert_chain(certfile, keyfile)
81+
82+
ssl_context.verify_mode = CERT_NONE
83+
ssl_context.check_hostname = False
84+
85+
return ssl_context
86+
87+
@classmethod
88+
def _create_ssl_context(cls, certfile: str, keyfile: str) -> SSLContext:
89+
return (
90+
cls.__create_circuitpython_ssl_context(certfile, keyfile)
91+
if implementation.name == "circuitpython"
92+
else cls.__create_cpython_ssl_context(certfile, keyfile)
93+
)
94+
7295
def __init__(
7396
self,
7497
socket_source: _ISocketPool,
@@ -483,9 +506,16 @@ def poll(self) -> str:
483506
# Connection reset by peer, try again later.
484507
if error.errno == ECONNRESET:
485508
return NO_REQUEST
509+
# Handshake failed, try again later.
486510
if error.errno == MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
487511
return NO_REQUEST
488512

513+
# CPython specific SSL related errors
514+
if implementation.name != "circuitpython" and isinstance(error, SSLError):
515+
# Ignore unknown SSL certificate errors
516+
if getattr(error, "reason", None) == "SSLV3_ALERT_CERTIFICATE_UNKNOWN":
517+
return NO_REQUEST
518+
489519
if self.debug:
490520
_debug_exception_in_handler(error)
491521

0 commit comments

Comments
 (0)