• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""
2  Copyright (c) 2024, The OpenThread Authors.
3  All rights reserved.
4
5  Redistribution and use in source and binary forms, with or without
6  modification, are permitted provided that the following conditions are met:
7  1. Redistributions of source code must retain the above copyright
8     notice, this list of conditions and the following disclaimer.
9  2. Redistributions in binary form must reproduce the above copyright
10     notice, this list of conditions and the following disclaimer in the
11     documentation and/or other materials provided with the distribution.
12  3. Neither the name of the copyright holder nor the
13     names of its contributors may be used to endorse or promote products
14     derived from this software without specific prior written permission.
15
16  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  POSSIBILITY OF SUCH DAMAGE.
27"""
28
29import asyncio
30import ssl
31import logging
32
33logger = logging.getLogger(__name__)
34
35
36class BleStreamSecure:
37
38    def __init__(self, stream):
39        self.stream = stream
40        self.ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
41        self.incoming = ssl.MemoryBIO()
42        self.outgoing = ssl.MemoryBIO()
43        self.ssl_object = None
44
45    def load_cert(self, certfile='', keyfile='', cafile=''):
46        if certfile and keyfile:
47            self.ssl_context.load_cert_chain(certfile=certfile, keyfile=keyfile)
48        elif certfile:
49            self.ssl_context.load_cert_chain(certfile=certfile)
50
51        if cafile:
52            self.ssl_context.load_verify_locations(cafile=cafile)
53
54    async def do_handshake(self, hostname):
55        self.ssl_object = self.ssl_context.wrap_bio(
56            incoming=self.incoming,
57            outgoing=self.outgoing,
58            server_side=False,
59            server_hostname=hostname,
60        )
61        while True:
62            try:
63                self.ssl_object.do_handshake()
64                break
65            # SSLWantWrite means ssl wants to send data over the link,
66            # but might need a receive first
67            except ssl.SSLWantWriteError:
68                output = await self.stream.recv(4096)
69                if output:
70                    self.incoming.write(output)
71                data = self.outgoing.read()
72                if data:
73                    await self.stream.send(data)
74                await asyncio.sleep(0.1)
75
76            # SSLWantRead means ssl wants to receive data from the link,
77            # but might need to send first
78            except ssl.SSLWantReadError:
79                data = self.outgoing.read()
80                if data:
81                    await self.stream.send(data)
82                output = await self.stream.recv(4096)
83                if output:
84                    self.incoming.write(output)
85                await asyncio.sleep(0.1)
86
87    async def send(self, bytes):
88        self.ssl_object.write(bytes)
89        encode = self.outgoing.read(4096)
90        await self.stream.send(encode)
91
92    async def recv(self, buffersize, timeout=1):
93        end_time = asyncio.get_event_loop().time() + timeout
94        data = await self.stream.recv(buffersize)
95        while not data and asyncio.get_event_loop().time() < end_time:
96            await asyncio.sleep(0.1)
97            data = await self.stream.recv(buffersize)
98        if not data:
99            logger.warning('No response when response expected.')
100            return b''
101
102        self.incoming.write(data)
103        while True:
104            try:
105                decode = self.ssl_object.read(4096)
106                break
107            # if recv called before entire message was received from the link
108            except ssl.SSLWantReadError:
109                more = await self.stream.recv(buffersize)
110                while not more:
111                    await asyncio.sleep(0.1)
112                    more = await self.stream.recv(buffersize)
113                self.incoming.write(more)
114        return decode
115
116    async def send_with_resp(self, bytes):
117        await self.send(bytes)
118        res = await self.recv(buffersize=4096, timeout=5)
119        return res
120