2023-10-31 06:31:59 +00:00
|
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
#
|
2017-06-04 19:50:49 +00:00
|
|
|
# Copyright (c) 2017 PySecretHandshake contributors (see AUTHORS for more details)
|
|
|
|
#
|
|
|
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
|
|
# of this software and associated documentation files (the "Software"), to deal
|
|
|
|
# in the Software without restriction, including without limitation the rights
|
|
|
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
|
|
# copies of the Software, and to permit persons to whom the Software is
|
|
|
|
# furnished to do so, subject to the following conditions:
|
|
|
|
#
|
|
|
|
# The above copyright notice and this permission notice shall be included in all
|
|
|
|
# copies or substantial portions of the Software.
|
|
|
|
#
|
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
|
|
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
|
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
|
|
# SOFTWARE.
|
|
|
|
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Networking functionality"""
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
from asyncio import StreamReader, StreamWriter, ensure_future, open_connection, start_server
|
|
|
|
from typing import AsyncIterator, Awaitable, Callable, List, Optional
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
from nacl.public import PrivateKey
|
|
|
|
from nacl.signing import SigningKey
|
|
|
|
from typing_extensions import Self
|
|
|
|
|
|
|
|
from .boxstream import BoxStream, UnboxStream, get_stream_pair
|
|
|
|
from .crypto import SHSClientCrypto, SHSCryptoBase, SHSServerCrypto
|
2017-06-04 19:50:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SHSClientException(Exception):
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Base exception class for client errors"""
|
2017-06-04 19:50:49 +00:00
|
|
|
|
|
|
|
|
2023-10-29 08:55:39 +00:00
|
|
|
class SHSDuplexStream:
|
|
|
|
"""SHS duplex stream"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def __init__(self) -> None:
|
|
|
|
self.write_stream: Optional[BoxStream] = None
|
|
|
|
self.read_stream: Optional[UnboxStream] = None
|
2018-02-04 21:19:15 +00:00
|
|
|
self.is_connected = False
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def write(self, data: bytes) -> None:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Write data to the write stream"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
assert self.write_stream
|
|
|
|
|
2017-06-04 19:50:49 +00:00
|
|
|
self.write_stream.write(data)
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
async def read(self) -> Optional[bytes]:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Read data from the read stream"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
assert self.read_stream
|
|
|
|
|
2017-06-04 19:50:49 +00:00
|
|
|
return await self.read_stream.read()
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def close(self) -> None:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Close the duplex stream"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
if self.write_stream:
|
|
|
|
self.write_stream.close()
|
|
|
|
|
2018-02-04 21:19:15 +00:00
|
|
|
self.is_connected = False
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def __aiter__(self) -> AsyncIterator[bytes]:
|
2023-10-30 05:46:19 +00:00
|
|
|
return self
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
async def __anext__(self) -> bytes:
|
2023-10-30 05:46:19 +00:00
|
|
|
msg = await self.read()
|
|
|
|
|
|
|
|
if msg is None:
|
|
|
|
raise StopAsyncIteration()
|
|
|
|
|
|
|
|
return msg
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2018-02-04 14:41:30 +00:00
|
|
|
|
2023-10-29 08:55:39 +00:00
|
|
|
class SHSEndpoint:
|
|
|
|
"""SHS endpoint"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def __init__(self) -> None:
|
|
|
|
self._on_connect: Optional[Callable[[SHSDuplexStream], Awaitable[None]]] = None
|
|
|
|
self.crypto: Optional[SHSCryptoBase] = None
|
2018-02-04 14:41:30 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def on_connect(self, cb: Callable[[SHSDuplexStream], Awaitable[None]]) -> None:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Set the function to be called when a new connection arrives"""
|
2023-10-30 04:47:28 +00:00
|
|
|
|
2017-06-05 18:41:44 +00:00
|
|
|
self._on_connect = cb
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def disconnect(self) -> None:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Disconnect the endpoint"""
|
2023-10-30 04:47:28 +00:00
|
|
|
|
2018-02-04 14:41:30 +00:00
|
|
|
raise NotImplementedError
|
|
|
|
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2018-02-04 14:41:30 +00:00
|
|
|
class SHSServer(SHSEndpoint):
|
2023-10-29 08:55:39 +00:00
|
|
|
"""SHS server"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def __init__(self, host: str, port: int, server_kp: SigningKey, application_key: Optional[bytes] = None):
|
2023-10-29 08:55:39 +00:00
|
|
|
super().__init__()
|
2017-06-04 19:50:49 +00:00
|
|
|
self.host = host
|
|
|
|
self.port = port
|
2023-10-30 04:47:28 +00:00
|
|
|
self.crypto: SHSServerCrypto = SHSServerCrypto(server_kp, application_key=application_key)
|
|
|
|
self.connections: List[SHSServerConnection] = []
|
|
|
|
|
|
|
|
async def _handshake(self, reader: StreamReader, writer: StreamWriter) -> None:
|
|
|
|
assert self.crypto
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2017-06-05 20:49:27 +00:00
|
|
|
data = await reader.readexactly(64)
|
2023-10-30 04:47:28 +00:00
|
|
|
|
2017-06-04 19:50:49 +00:00
|
|
|
if not self.crypto.verify_challenge(data):
|
2023-10-29 08:47:57 +00:00
|
|
|
raise SHSClientException("Client challenge is not valid")
|
2017-06-04 19:50:49 +00:00
|
|
|
|
|
|
|
writer.write(self.crypto.generate_challenge())
|
|
|
|
|
2017-06-05 20:49:27 +00:00
|
|
|
data = await reader.readexactly(112)
|
2023-10-30 04:47:28 +00:00
|
|
|
|
2017-06-04 19:50:49 +00:00
|
|
|
if not self.crypto.verify_client_auth(data):
|
2023-10-29 08:47:57 +00:00
|
|
|
raise SHSClientException("Client auth is not valid")
|
2017-06-04 19:50:49 +00:00
|
|
|
|
|
|
|
writer.write(self.crypto.generate_accept())
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
async def handle_connection(self, reader: StreamReader, writer: StreamWriter) -> None:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Handle incoming connections"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
assert self.crypto
|
|
|
|
|
2017-06-04 19:50:49 +00:00
|
|
|
self.crypto.clean()
|
|
|
|
await self._handshake(reader, writer)
|
|
|
|
keys = self.crypto.get_box_keys()
|
|
|
|
self.crypto.clean()
|
|
|
|
|
2018-02-04 14:41:30 +00:00
|
|
|
conn = SHSServerConnection.from_byte_streams(reader, writer, **keys)
|
|
|
|
self.connections.append(conn)
|
2017-06-04 19:50:49 +00:00
|
|
|
|
|
|
|
if self._on_connect:
|
2023-10-30 04:47:28 +00:00
|
|
|
ensure_future(self._on_connect(conn))
|
2018-02-04 14:41:30 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
async def listen(self) -> None:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Listen for connections"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
await start_server(self.handle_connection, self.host, self.port)
|
2018-02-04 14:41:30 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def disconnect(self) -> None:
|
2018-02-04 14:41:30 +00:00
|
|
|
for connection in self.connections:
|
|
|
|
connection.close()
|
2017-06-04 19:50:49 +00:00
|
|
|
|
|
|
|
|
2018-02-04 14:41:30 +00:00
|
|
|
class SHSServerConnection(SHSDuplexStream):
|
2023-10-29 08:55:39 +00:00
|
|
|
"""SHS server connection"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def __init__(self, read_stream: UnboxStream, write_stream: BoxStream):
|
2023-10-29 08:55:39 +00:00
|
|
|
super().__init__()
|
2023-10-30 04:47:28 +00:00
|
|
|
|
2018-02-04 14:41:30 +00:00
|
|
|
self.read_stream = read_stream
|
|
|
|
self.write_stream = write_stream
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2018-02-04 14:41:30 +00:00
|
|
|
@classmethod
|
2023-10-30 04:47:28 +00:00
|
|
|
def from_byte_streams(cls, reader: StreamReader, writer: StreamWriter, **keys: bytes) -> Self:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Create a server connection from an existing byte stream"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
box_reader, box_writer = get_stream_pair(reader, writer, **keys)
|
2023-10-29 08:55:39 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
return cls(box_reader, box_writer)
|
2018-02-04 14:41:30 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SHSClient(SHSDuplexStream, SHSEndpoint):
|
2023-10-29 08:55:39 +00:00
|
|
|
"""SHS client"""
|
|
|
|
|
|
|
|
def __init__( # pylint: disable=too-many-arguments
|
2023-10-30 04:47:28 +00:00
|
|
|
self,
|
|
|
|
host: str,
|
|
|
|
port: int,
|
|
|
|
client_kp: SigningKey,
|
|
|
|
server_pub_key: bytes,
|
|
|
|
ephemeral_key: Optional[PrivateKey] = None,
|
|
|
|
application_key: Optional[bytes] = None,
|
2023-10-29 08:55:39 +00:00
|
|
|
):
|
2018-02-04 14:41:30 +00:00
|
|
|
SHSDuplexStream.__init__(self)
|
|
|
|
SHSEndpoint.__init__(self)
|
2017-06-04 19:50:49 +00:00
|
|
|
self.host = host
|
|
|
|
self.port = port
|
2023-10-30 04:47:28 +00:00
|
|
|
self.writer: Optional[StreamWriter] = None
|
|
|
|
self.crypto: SHSClientCrypto = SHSClientCrypto(
|
|
|
|
client_kp,
|
|
|
|
server_pub_key,
|
|
|
|
ephemeral_key=ephemeral_key or PrivateKey.generate(),
|
|
|
|
application_key=application_key,
|
2023-10-29 08:47:57 +00:00
|
|
|
)
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
async def _handshake(self, reader: StreamReader, writer: StreamWriter) -> None:
|
2017-06-04 19:50:49 +00:00
|
|
|
writer.write(self.crypto.generate_challenge())
|
|
|
|
|
2017-06-05 20:49:27 +00:00
|
|
|
data = await reader.readexactly(64)
|
2023-10-30 04:47:28 +00:00
|
|
|
|
2017-06-04 19:50:49 +00:00
|
|
|
if not self.crypto.verify_server_challenge(data):
|
2023-10-29 08:47:57 +00:00
|
|
|
raise SHSClientException("Server challenge is not valid")
|
2017-06-04 19:50:49 +00:00
|
|
|
|
|
|
|
writer.write(self.crypto.generate_client_auth())
|
2017-06-05 20:49:27 +00:00
|
|
|
data = await reader.readexactly(80)
|
2023-10-30 04:47:28 +00:00
|
|
|
|
2017-06-04 19:50:49 +00:00
|
|
|
if not self.crypto.verify_server_accept(data):
|
2023-10-29 08:47:57 +00:00
|
|
|
raise SHSClientException("Server accept is not valid")
|
2017-06-04 19:50:49 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
async def open(self) -> None:
|
2023-10-29 08:55:39 +00:00
|
|
|
"""Open the TCP connection"""
|
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
reader, writer = await open_connection(self.host, self.port)
|
2017-08-01 17:31:24 +00:00
|
|
|
await self._handshake(reader, writer)
|
2017-06-04 19:50:49 +00:00
|
|
|
|
|
|
|
keys = self.crypto.get_box_keys()
|
|
|
|
self.crypto.clean()
|
|
|
|
|
|
|
|
self.read_stream, self.write_stream = get_stream_pair(reader, writer, **keys)
|
|
|
|
self.writer = writer
|
2018-02-04 21:19:15 +00:00
|
|
|
self.is_connected = True
|
2023-10-29 08:55:39 +00:00
|
|
|
|
2017-06-05 18:41:44 +00:00
|
|
|
if self._on_connect:
|
2023-10-30 04:47:28 +00:00
|
|
|
await self._on_connect(self)
|
2018-02-04 14:41:30 +00:00
|
|
|
|
2023-10-30 04:47:28 +00:00
|
|
|
def disconnect(self) -> None:
|
2018-02-04 14:41:30 +00:00
|
|
|
self.close()
|